安卓开发

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

2018-10-11  本文已影响9人  蓝不蓝编程

背景:

在有些情况下,需要通过代码自动向页面内增加控件,而不是事先在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);
        }

效果:

安卓开发技术分享: https://www.jianshu.com/p/442339952f26

上一篇 下一篇

猜你喜欢

热点阅读