Android 在布局容器中动态添加控件

66 篇文章 0 订阅
30 篇文章 0 订阅

这里,通过一个小demo,就可以掌握在布局容器中动态添加控件,以动态添加Button控件为例,添加其他控件同样道理。

1、addView

添加控件到布局容器

2、removeView

在布局容器中删掉已有的控件

3、使用,来个小demo就明白了

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

public class MainActivity extends Activity {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

 

        // 生成一个LinearLayout,作为布局容器来动态添加3个Button

        final LinearLayout layout = new LinearLayout(this);

        layout.setOrientation(LinearLayout.VERTICAL);

        setContentView(layout);

 

        // 生成3个Button

        final Button btn1 = new Button(this);

        btn1.setText("1");

        btn1.setText("Button1");

        final Button btn2 = new Button(this);

        btn2.setText("2");

        btn2.setText("Button2");

        final Button btn3 = new Button(this);

        btn3.setText("3");

        btn3.setText("Button3");

 

        // 动态把三个Button添加到

        layout.addView(btn1);

        layout.addView(btn2);

        layout.addView(btn3);

 

        // 点击按钮时,先把原来在布局容器layout上的删掉,再添加上局容器layout,这样本次添加的控件就会排序到最后,以理解动态添加控件的思路

        btn1.setOnClickListener(new OnClickListener() {

 

            @Override

            public void onClick(View arg0) {

                layout.removeView(btn1);

                layout.addView(btn1);

            }

        });

 

        // 同btn1一样道理

        btn2.setOnClickListener(new OnClickListener() {

 

            @Override

            public void onClick(View arg0) {

                layout.removeView(btn2);

                layout.addView(btn2);

            }

        });

 

        // 同btn1一样道理

        btn3.setOnClickListener(new OnClickListener() {

 

            @Override

            public void onClick(View arg0) {

                layout.removeView(btn3);

                layout.addView(btn3);

            }

        });

        setContentView(layout);

    }

 

}

 4、上图

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值