I would like to add a button switch similar to jellybean native look. (Blue/gray switch at the top of the view)
Documentation shows how to create a menu there or add icons, but it does not say, how to add a custom elements. eg. a switch. http://developer.android.com/guide/topics/ui/actionbar.html
All action buttons and other items available in the action overflow are defined in an XML menu resource. To add actions to the action bar, create a new XML file in your project's res/menu/ directory. The app:showAsAction attribute specifies whether the action should be shown as a button on the app bar.
Create a layout for the switch switch_layout.xml
. Custom layouts for menu should always be RelativeLayout
<?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" > <Switch android:id="@+id/switchForActionBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" /> </RelativeLayout>
Then, in your mainmenu.xml
add the item as follows
<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/myswitch" android:title="" android:showAsAction="always" android:actionLayout="@layout/switch_layout" /> </menu>
And in your activity, inflate the mainmenu.xml
as you always do
getMenuInflater().inflate(R.menu.mainmenu, menu); return true;
Finally figured out my problem: for those that's using the new AppCompat, you should be using android.support.v7.widget.SwitchCompat
instead of Switch
on the switch layout...otherwise, it won't show on the ActionBar
(assumed you're using AppCompat ActionBar as well), well, the actionLayout attribute doesn't work, it has to be set in the code.
<?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="match_parent" android:layout_height="wrap_content" android:text="" /> </RelativeLayout>
Then set the layout in the code:
@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); MenuItem item = menu.findItem(R.id.on_off_switch); item.setActionView(R.layout.on_off_switch); return true; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With