Reputation: 3507
I want to make a custom switch in the action bar. This is my menu xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:autolux="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/actionbar_notification_switch"
android:title=""
android:actionLayout="@layout/notification_switch"
autolux:showAsAction="always"/>
</menu>
This is my custom notification switch xml notification_switch.xml:
<?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="wrap_content"
android:orientation="horizontal">
<Switch xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/color"
android:textOff="OFF"
android:textOn="ON"
android:thumb="@drawable/navigation_switch_selector"
android:checked="false"
android:id="@+id/actionbar_notification" />
</RelativeLayout>
And this is what I call from my activity:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.notification_menu, menu);
return true;
}
But my actionbar does not show my custom switch (or any other component if I put it in the notification_switch.xml). Also I am able to set the main.xml menu as my menu wich only uses an icon and that works. That code is:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:autolux="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_bar_filter"
android:icon="@drawable/ic_sort"
android:title="@string/action_settings"
autolux:showAsAction="always" />
</menu>
I can't seem to figure out what is going wrong with my custom components. Any help will be appreciated. (additional info is: Min Sdk Version 14, Compile Sdk Version 19, Build Tools Version 20
Upvotes: 0
Views: 463
Reputation: 18977
I hope it helps:
remove:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.notification_menu, menu);
return true;
}
then in your onCreate method
:
ActionBar mActionBar = getActionBar();
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.notification_switch, null);
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
reference:
http://javatechig.com/android/actionbar-with-custom-view-example-in-android
if you are using actionBarCompat
use getSupportActionBar
instead of getActionBar
Upvotes: 1