Abhilash anand
Abhilash anand

Reputation: 127

How to add material design library switch in the action bar

How to insert com.gc.materialdesign.views.Switch in the Actionbar using MenuInflater??

Below is the code for inflating the android default switch.

This is my onCreateOptionsMenu

@Override
public boolean onCreateOptionsMenu(Menu menu)
   {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    MenuItem item = menu.findItem(R.id.myswitch);
    switchButton = (Switch)item.getActionView();
   }

This is my menu_main.xml

<menu  
    xmlns:app="http://schemas.android.com/apk/res-auto"                     
    xmlns:android="http://schemas.android.com/apk/res/android"
    >

    <item
        android:id="@+id/myswitch"
        android:title="off/on"
        app:showAsAction="always"
        app:actionLayout="@layout/switchlayout"
        app:actionViewClass="android.widget.Switch"
        />
</menu>

This is the switch layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <Switch
        android:layout_centerVertical="true"
        android:id="@+id/mySwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="off/on toasts" />
</RelativeLayout>

Any help is appreciated!

Upvotes: 0

Views: 661

Answers (2)

Jenisha Makadiya
Jenisha Makadiya

Reputation: 832

Replace your Switch code with below code

<com.gc.materialdesign.views.Switch
    android:id="@+id/mySwitch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:background="#1E88E5" />

and Replace item code with

<item
    android:id="@+id/menu_switch"
    android:title="off/on"
    app:showAsAction="always"
    app:actionLayout="@layout/switchlayout"/>

Upvotes: 3

moofins
moofins

Reputation: 150

Try replacing <Switch in your switchlayout.xml with <com.gc.materialdesign.views.Switch. Also, you don't need to specify app:actionViewClass since you're already providing a layout.

Upvotes: 0

Related Questions