Reputation: 119
I'd like to place a switch on the actionbar of my main menu. The empty space is there i can click on it, but there is no switch. What can be the solution?
Thanks in advance!
switch_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/switchView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<android.support.v7.widget.SwitchCompat
android:id="@+id/switchForActionBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
activtiy_main_action.xml:
<item
android:id="@+id/myswitch"
android:title=""
app:showAsAction="always"
android:actionLayout="@layout/switch_layout">
</item>
MainActivity.java
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinf = getMenuInflater();
menuinf.inflate(R.menu.activity_main_action, menu);
//getMenuInflater().inflate(R.menu.mainmenu, menu);
return super.onCreateOptionsMenu(menu);
}
Upvotes: 2
Views: 138
Reputation: 69724
change this in your menu
use app:actionLayout="@layout/switch_layout"
insted of
android:actionLayout="@layout/switch_layout"
<item
android:id="@+id/myswitch"
android:title=""
app:showAsAction="always"
app:actionLayout="@layout/switch_layout">
</item>
and for access your switch use below code
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.badge_menu, menu);
MenuItem item = menu.findItem(R.id.myswitch);
MenuItemCompat.setActionView(item, R.layout.switch_layout);
RelativeLayout notifCount = (RelativeLayout) MenuItemCompat.getActionView(item)
Switch switch_button = (Switch) notifCount.findViewById(R.id.switchForActionBar);
switch_button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
// true if the switch is in the On position
}
});
return super.onCreateOptionsMenu(menu);
}
Upvotes: 2