【发布时间】:2015-04-13 19:33:51
【问题描述】:
我希望我的应用程序提供添加按钮的功能,如 Avadhani Y 在How to create Button Dynamically in android? 中描述的那样
我复制了这段代码,当我按下 + 符号时会出现该按钮,但它不是永久性的。当我关闭应用程序并再次打开它时,按钮消失了。
对于一个最小的工作示例,我
- 创建了一个由 Eclipse 设置的空白 Android 应用程序项目
-
将How to create Button Dynamically in android? 中描述的部分方法添加到 MainActivity.java (第二种情况带有减号按钮会产生几条错误消息,所以我省略了。):
public void onClick(View v){ switch(v.getId()){ case (R.id.plusbutton): Button myButton = new Button(this); myButton.setText("Add Me"); LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout); LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); ll.addView(myButton, lp); break; } } 导入了必要的包。实际上我不确定我是否为带有 LayoutParams 的行选择了正确的 - eclipse 列出了几个包 - 我选择了
android.view.ViewGroup.LayoutParams- 将activity_main.xml 文件更改为以下文件。
- 在 strings.xml 文件中添加了一些字符串
我的 activity_main.xml 文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/buttonlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.button_test.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/plusbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="@string/plus" />
</LinearLayout>
【问题讨论】:
标签: java android xml eclipse button