一般来说,做android开发,用xml布局比较多,相对于用代码来布局还是多一些,但是也有一些场景需要用到代码动态添加布局,一些不确定的场景就需要了。

主要代码如下

public class MainActivity extends AppCompatActivity {
    private ConstraintLayout layout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initControl();
    }

    private void initView() {
        layout = new ConstraintLayout(this);
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT,ConstraintLayout.LayoutParams.MATCH_PARENT);
        layout.setLayoutParams(layoutParams);
        layout.setBackgroundColor(Color.CYAN);
        this.setContentView(layout);
    }

    private void initControl() {
        // 设置布局并且设置约束
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,ConstraintLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;

        // 添加textview控件
        TextView textView = new TextView(this);
        textView.setText("测试代码动态添加控件!");
        textView.setTextColor(Color.BLACK);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getBaseContext(),((TextView)v).getText().toString(),Toast.LENGTH_LONG).show();
            }
        });
        // 设置布局
        textView.setId((int)8888);
        textView.setLayoutParams(layoutParams);
        layout.addView(textView);

        // 添加第二个控件
        ConstraintLayout.LayoutParams layoutParams1 = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,ConstraintLayout.LayoutParams.WRAP_CONTENT);
        layoutParams1.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams1.topToBottom = (int)8888;
                layoutParams1.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;

        TextView textView1 = new TextView(this);
        textView1.setText("测试代码动态添加控件2!");
        textView1.setTextColor(Color.BLACK);
        textView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getBaseContext(),((TextView)v).getText().toString(),Toast.LENGTH_LONG).show();
            }
        });
        textView1.setLayoutParams(layoutParams1);
        layout.addView(textView1);
    }

实现效果如下图所示:

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐