Switch (button) Throws Nullpointerexception
I know this question already exists, but I tried serveral solutions and none worked for me. In my case, I need a Switch Button in the ActionBar. I tried to manually add a minSdk V
Solution 1:
Follow the answer by 'ρяσѕρєя K' but change his following line of code:
MenuItemitem= menu.findItem(R.id.switch_button);
to this:
MenuItem item = menu.findItem(R.id.myswitch); //the id was changed!
That should get rid of the NullPointerException, hope this helps :)
So you should have something like this:
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_minepedia_main);
}
@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_actions, menu);
MenuItem item = menu.findItem(R.id.myswitch);
switchButton = (Switch)item.getActionView();
switchButton.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener({
@OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//The following is a local boolean variable if (isChecked) {
ONLINE_MODE_ENABLED = true;
} else {
ONLINE_MODE_ENABLED = false;
}
}
});
returnsuper.onCreateOptionsMenu(menu);
}
Additionally change this line:
android:actionLayout="@layout/switch_layout"
to this:
android:actionViewClass="android.widget.Switch"
That is within your menu xml. If you apply that change then you are using the switch button provided by android and that must work.
Solution 2:
Because Switch
button is inside main_actions.xml
so you should use menu.findItem
in onCreateOptionsMenu
to access views from Menu as:
@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
MenuInflaterinflater= getMenuInflater();
inflater.inflate(R.menu.main_actions, menu);
MenuItemitem= menu.findItem(R.id.switch_button);
switchButton = (Switch)item.getActionView();
returnsuper.onCreateOptionsMenu(menu);
}
Post a Comment for "Switch (button) Throws Nullpointerexception"