gpt4 book ai didi

java - 无法将 setOnClickListener 添加到抽屉导航中的按钮

转载 作者:行者123 更新时间:2023-12-02 08:40:09 25 4
gpt4 key购买 nike

我想在按下抽屉导航内的按钮时创建一个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>

如何正确引用抽屉导航中的按钮以便事件监听器正常工作?

最佳答案

您不能以这种方式对菜单项使用 clicklistener,但您可以使用 setNavigationItemSelectedListener:

首先在您的 Activity 中实现监听器:

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;
}

关于java - 无法将 setOnClickListener 添加到抽屉导航中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61428226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com