当我按下导航抽屉内的按钮时,我想创建一个AlertDialog
。我从我的activity.java文件的onCreate
函数中编写了以下代码
Button chooseBuildings = findViewById(R.id.chooseBuilding);
final String[] colors = {"red", "green", "blue", "black"};
chooseBuildings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(StartNavigationActivity.this);
builder.setTitle("Choose a building");
builder.setItems(colors, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
});
当检查我的logcat时,我得到一个NullPointerException
:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
这是我的menu.xml
文件:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="@+id/settings"
android:icon="@drawable/ic_settings"
android:title="Settings"
/>
<item
android:id="@+id/chooseBuilding"
android:icon="@drawable/ic_change_building"
android:title="Choose Building"
/>
<item
android:id="@+id/feedback"
android:title="Send Feedback"
android:icon="@drawable/ic_feedback"
/>
<item
android:id="@+id/help"
android:title="Help"
android:icon="@drawable/ic_help"
/>
</menu>
如何正确引用导航抽屉中的按钮,以便事件监听器正常工作?
答案 0 :(得分:1)
您不能以这种方式将clicklistener用于菜单项,而可以使用setNavigationItemSelectedListener:
在您的活动中首先实现侦听器:
public class YourActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
然后,为导航抽屉设置侦听器:
NavigationView mNavigationView = findViewById(R.id.navigation view id);
mNavigationView.setNavigationItemSelectedListener(this);
最后,赶上事件:
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.chooseBuilding: {
AlertDialog.Builder builder = new AlertDialog.Builder(StartNavigationActivity.this);
builder.setTitle("Choose a building");
builder.setItems(colors, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
}
return true;
}