安卓动态添加控件_向LinearLayout中增加控件

背景:

       在有些情况下,需要通过代码自动向页面内增加控件,而不是事先在xml文件中写好。本文介绍将LinearLayout中增加控件。

解决方案:

    1.添加单个控件样例      

LinearLayout layout = findViewById(R.id.topLayout);
TextView textView = new TextView(this);
textView.setText("测试");
layout.addView(textView);

      效果:

     

    2.添加多个控件样例 

LinearLayout layout = findViewById(R.id.topLayout);
        for(int i=0;i<5;i++)
        {
            TextView textView = new TextView(this);
            textView.setText("测试"+i);
            layout.addView(textView);
        }

      效果:  

      

猜你喜欢

转载自blog.csdn.net/yinxing2008/article/details/82998376
今日推荐