如何动态添加Activity

如何动态添加Activity,第1张

动态增加控件的基本思路就是:实例化控件->布局.addView(控件) ->OnCreat中绑定布局控件 setContentView(布局)

例1:在LinearLayout中动态增加Button,EditText等控件,并且点击Button后,动态增加EditText等控件。

Java代码

1.@Override

2.protected void onCreate(Bundle savedInstanceState) {

3.super.onCreate(savedInstanceState)

4.final LinearLayout linearLayout=new LinearLayout(this)

5.linearLayout.setOrientation(LinearLayout.VERTICAL)

6.

7.LinearLayout linearLayout1 = new LinearLayout(this)

8.linearLayout1.setOrientation(LinearLayout.VERTICAL)

9.

10.Button button1= new Button(this)

11.button1.setText("增加新项目")

12.

13.Button button2 = new Button(this)

14.button2.setText("增加新组")

15.

16.linearLayout.addView(button1)

17.linearLayout.addView(button2)

18.

19.//设定按钮单击监听器,动态增加控件.

20.button2.setOnClickListener(new Button.OnClickListener(){

21.public void onClick(View v) {

22.Context context = v.getContext()

23.LinearLayout linearLayout2 = new LinearLayout(context)

24.linearLayout2.setOrientation(LinearLayout.HORIZONTAL)

25.

26.EditText groupNameEditText = new EditText(context)

27.//设置控件大小.

28.groupNameEditText.setWidth(160)

29.

30.ImageButton imagebutton1 = new ImageButton(context)

31.Button saveButton = new Button(context)

32.Button exitButton = new Button(context)

33.

34.linearLayout2.addView(groupNameEditText)

35.linearLayout2.addView(imagebutton1)

36.linearLayout2.addView(saveButton)

37.linearLayout2.addView(exitButton)

38.linearLayout.addView(linearLayout2)

39.

40.}

41.})

42.

43.setContentView(linearLayout)

44.}

45.

在Fragment中添加一个布局容器,并设置ID,在Activity中findbyview找到后,就可以动态添加了。

代码如下:

<?xml version="1.0"encoding="utf-8"?>

<LinearLayout xmlns:android="

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<Button

android:id="@+id/first_button"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/first_button"/>

<Button

android:id="@+id/second_button"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/second_button"/>

<Button

android:id="@+id/third_button"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/third_button"/>

</LinearLayout>


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/7967346.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-12
下一篇2023-04-12

发表评论

登录后才能评论

评论列表(0条)

    保存