ConstraintLayout 动态添加控件

under Android  tag     Published on July 8th , 2021 at 12:07 pm

add_view.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/cl">

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/iv"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:background="@color/teal_200"/>
</androidx.constraintlayout.widget.ConstraintLayout>

AddViewActivity.java

public class AddViewActivity extends AppCompatActivity {
    ImageView iv;
    ConstraintLayout cl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_view.xml);

        iv = findViewById(R.id.iv);
        cl = findViewById(R.id.cl);

        ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(100, 100);
        
        lp.startToStart = R.id.cl;
        lp.topToTop = R.id.cl;
        
        lp.setMargins(50, 50, 0, 0);
        TextView tv = new TextView(this);
        tv.setBackgroundColor(Color.BLUE);
        tv.setLayoutParams(lp);
        cl.addView(tv);
    }
}

本文由 surface 创作,采用 知识共享署名4.0 国际许可协议进行许可,转载前请务必署名
  文章最后更新时间为:July 8th , 2021 at 12:07 pm
分享到:Twitter  Weibo  Facebook