Reputation: 20616
I'm trying to add a Switch
widget on my ActionBar
but when I try to implement it it doesn't show or if it does, my ActionBart
title dissapears.
What I've done is :
I've created a Layout
for this Switch
?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<android.support.v7.widget.SwitchCompat
android:id="@+id/switchAB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
And then on my menu_main.xml
I've added this :
<item
android:id="@+id/switchId"
android:title=""
app:showAsAction="ifRoom"
android:actionLayout="@layout/swipe_wifi"
/>
I've changed android
to app
because on help says so
Then on my ActivityMain onCreateOptionsMenu()
if added this to make a fast test
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
switchAB = (Switch)menu.findItem(R.id.switchId)
.getActionView().findViewById(R.id.switchAB);
switchAB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
Toast.makeText(getApplication(), "ON", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplication(), "OFF", Toast.LENGTH_SHORT)
.show();
}
}
});
return true;
}
But it's giving to me a NPE
on this lane
switchAB = (Switch)menu.findItem(R.id.switchId)
//NPE--> .getActionView().findViewById(R.id.switchAB);
Shall I change something on my code?
Upvotes: 0
Views: 482
Reputation: 25194
Try using app:actionLayout
too:
<item
android:id="@+id/switchId"
android:title=""
app:showAsAction="ifRoom"
app:actionLayout="@layout/swipe_wifi"
/>
It should be noted also that you are casting the view to android.widget.Switch
, while in your layout you have a android.support.v7.widget.SwitchCompat
(and that is a good choice, since Switch
was added in API14).
Upvotes: 2