gpt4 book ai didi

java - FindItem(R.id.*) 抛出 NullPointerException

转载 作者:太空宇宙 更新时间:2023-11-04 09:28:08 26 4
gpt4 key购买 nike

我想为我的菜单项添加onMenuItemClickListener。问题是,当我尝试在 onCreateOptionsMenu() 之外访问 menu.findItem(R.id.*) 时,我总是收到 NullPointerException。由于某种原因,菜单项仍然无法用于任何其他功能,我不知道为什么......

    public Menu items_type;


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.items_type, menu);
items_type=menu;
return true;
}

public boolean onPrepareOptionsMenu(Menu menu) {
items_type.clear();
MenuItem.OnMenuItemClickListener common = new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
if(items_type.findItem(R.id.filename).isChecked() && menuItem.getItemId()==R.id.tracktitle)
{
items_type.findItem(R.id.tracktitle).setChecked(true);
items_type.findItem(R.id.filename).setChecked(false);
}
else if(items_type.findItem(R.id.tracktitle).isChecked() && menuItem.getItemId()==R.id.filename)
{
items_type.findItem(R.id.filename).setChecked(true);
items_type.findItem(R.id.tracktitle).setChecked(false);
}
return true;
}
};
items_type.findItem(R.id.tracktitle).setOnMenuItemClickListener(common);
items_type.findItem(R.id.filename).setOnMenuItemClickListener(common);
return true;
}

public void onCreate(Bundle savedInstanceState) {
...
}

/res/menu/items_type.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<group android:id="@id/group"
android:checkableBehavior="single">
<item
android:id="@id/filename"
android:title=" File Names"
app:showAsAction="never"/>
<item
android:id="@id/tracktitle"
android:title="ID3 Titles"
app:showAsAction="never"/>

</group>
</menu>

最佳答案

像这样处理菜单点击事件更好 @覆盖 公共(public)无效onCreateOptionsMenu(菜单菜单,MenuInflater inflater){ super.onCreateOptionsMenu(菜单,充气器); getMenuInflater().inflate(R.menu.items_type, 菜单); }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int i = item.getItemId();
if (i == android.R.id.home) {
} else if (i == R.id.action_share_pdf) {
}
return super.onOptionsItemSelected(item);
}

关于java - FindItem(R.id.*) 抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57435384/

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