我对如何检查 Activity 菜单文件中的复选框感到困惑,而不是它的布局文件。首先,我有下面的代码,但使用的是 findViewById(R.id.uniformScale);
而不是 findViewById(R.menu.dressing_room).findViewById(R.id.uniformScale);
但这引发了 nullPointerException,所以我添加了 findViewById(R.menu.dressing_room)
但这会导致相同的错误。我知道我必须引用菜单文件中的复选框,因为它不在布局文件中,但我不确定如何引用。或者我将它添加到布局文件中,但我也不知道该怎么做。注意:它们可能是 radioButtons 因为 checkableBehavior="single"但我尝试将类型更改为 RadioButton 并抛出相同的异常。谢谢。
在 Activity 的菜单文件中:
<item
android:title="Sticker Settings"
android:id="@+id/action_cancel1"
android:icon="@drawable/ic_action_settings">
<menu>
<group android:checkableBehavior="single"
>
<item android:id="@+id/uniformScale"
android:title="Change Size"
android:checked="true" />
<item android:id="@+id/rotation"
android:title="Rotate"
android:checked="false" />
</group>
</menu>
</item>
在 Activity 中:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mainActivity, menu);
checkCheckboxes();
return true;
}
private void checkCheckboxes(){
CheckBox checkBox1 = (CheckBox) findViewById(R.menu.dressing_room).findViewById(R.id.uniformScale);
if (checkBox1.isChecked()) {
photoSorter.setRotate(1);
photoSorter.setAnisotropic(2);
}
else{
checkBox1.setChecked(true);
photoSorter.setRotate(2);
photoSorter.setAnisotropic(1);
}
}
编辑尝试黑带回答:
private void checkCheckboxes(Menu menu){
MenuItem checkBox1 = (MenuItem) menu.getItem(R.id.uniformScale);
if (checkBox1.isChecked()) {
photoSorter.setRotate(1);
photoSorter.setAnisotropic(2);
}
else{
//checkBox1.setChecked(true);
photoSorter.setRotate(2);
photoSorter.setAnisotropic(1);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mainActivity, menu);
checkCheckboxes(menu);
return true;
}
最佳答案
改变
private void checkCheckboxes()
到
private void checkCheckboxes(Menu menu)
并使用 menu.findItem(R.id.uniformScale)
检索元素
关于android - 检查复选框 nullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21475268/