【问题标题】:Null Pointer exception to a button in a Dialog -- Android -- JAVA对话框中按钮的空指针异常 -- Android -- JAVA
【发布时间】:2021-08-25 20:59:14
【问题描述】:

这已被问了一百万次,但我无法让我的代码工作:

public class MainActivity extends AppCompatActivity {

//private static final String LOG_TAG = "SongList";
Dialog mDialog;
Button button;
static final String LOG_TAG = "SONG_APP";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Setup Floating Action Button that is used by user to open EditorActivity
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            mDialog = new Dialog (MainActivity.this);
            button = mDialog.findViewById(R.id.button);
            
            mDialog.setContentView(R.layout.fab_search_popup);
            mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            try {
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.e(LOG_TAG,"Button is clicked");
                        mDialog.dismiss();
                    }
                });
                mDialog.show();

            } catch (NullPointerException e) {
                Log.e(LOG_TAG, "Null Pointer Exception");
                }
        }
    });

}

}

对话框的布局文件是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="300dp"
    android:layout_height="400dp"
    android:layout_gravity="center"
    android:padding="12dp">

    <Button
        android:id="@+id/button"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_centerInParent="true"
        android:background="@color/teal_200"
        android:gravity="center"
        android:text="Button" />

</RelativeLayout>

我仍然在下面的行中得到 Null value for button 并且不知道为什么:

button = mDialog.findViewById(R.id.button);

我已经将我的代码精简到了骨子里,但无法弄清楚它为什么为空。 请帮忙

【问题讨论】:

  • 您是否调试过代码并检查您在R.id.button 中获得了什么值?

标签: java android nullpointerexception dialog


【解决方案1】:

在获得对按钮的引用之后,您正在膨胀对话框布局。它返回 null 因为您的对话框对象在膨胀之前没有 ID 为“button”的按钮视图

你应该把顺序改成这个

mDialog.setContentView(R.layout.fab_search_popup);
button = mDialog.findViewById(R.id.button);

如果有帮助,请告诉我!

【讨论】:

  • 谢谢。有用。我现在更好地理解了视图膨胀的概念。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
相关资源
最近更新 更多