[英]Having trouble dynamically creating buttons in Android Studio
我是Android的新手,我不知道如何動態地向現有布局添加按鈕。 我將在SO上的另一個問題中找到的一些示例代碼修補到一個hello world默認項目中。
onCreate方法:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button myButton = new Button(this);
myButton.setText("Add Me");
RelativeLayout ll = (RelativeLayout)findViewById(R.id.main_layout);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
setContentView(R.layout.activity_main);
}
布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:id="@+id/main_layout"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/cat_1"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="26dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:id="@+id/cat_2"
android:layout_alignBottom="@+id/cat_1"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="65dp"
android:layout_marginEnd="65dp" />
</RelativeLayout>
當我注釋掉添加按鈕部分時,該項目將正常工作,所以我知道這就是問題所在。 而且我會粘貼一些調試信息,但是logcat的“ debug”過濾器非常冗長,即使程序沒有運行也要不斷更新。 當我在調試模式下運行手機時,手機顯示錯誤消息幾分之一秒,然后出現消息“應用程序已停止工作”。
setContentView
應該在super之后立即完成。 否則,任何時候調用findViewById
都將返回空指針。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button myButton = new Button(this);
myButton.setText("Add Me");
RelativeLayout ll = (RelativeLayout)findViewById(R.id.main_layout);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
}
在設置內容視圖之前,您正在執行findViewById。 這意味着找不到任何視圖。 因此,當您嘗試使用該視圖時,會出現空指針異常
LinearLayout ll = (LinearLayout) findViewById(R.id.main_layout);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for(int i=0;i<30;i++){
Button myButton = new Button(this);
myButton.setText("Add Me");
myButton.setId(i);
ll.addView(myButton, lp);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.