在 Android Studio 中动态创建按钮时遇到问题

Jpa*_*ish 1 java android dynamic button android-relativelayout

我是 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);
    }
Run Code Online (Sandbox Code Playgroud)

布局:

<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>
Run Code Online (Sandbox Code Playgroud)

当我注释掉添加按钮部分时,该项目有效,所以我知道这就是问题所在。我会粘贴一些调试信息,但 logcat 的“调试”过滤器非常冗长,即使程序没有运行也会不断更新。当我在调试模式下运行它时,手机在出现“应用程序已停止工作”消息之前显示错误几分之一秒。

mat*_*red 5

setContentView应该在超级之后立即完成。否则任何时候你调用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);
}
Run Code Online (Sandbox Code Playgroud)