2015-07-11 44 views
0

如何使用MenuInflaterActionbar中插入com.gc.materialdesign.views.Switch如何在操作栏中添加材料设计库开关

下面是对默认开关进行充气的代码。

这是我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(); 
    } 

这是我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> 

这是开关布局

<?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> 

任何帮助表示赞赏!

+0

你在找这个android.support.v7.widget.SwitchCompat更换项目的代码? – sachithkn

+0

不,我没有找SwitchCompat的开关。谢谢你的回应:) –

回答

3

替换为你的交换机代码下面的代码

<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" /> 

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

谢谢你的回复。我标记为正确:) –

+0

谢谢。分享是关怀:) –

0

尝试用<com.gc.materialdesign.views.Switch替换switchlayout.xml中的<Switch。此外,由于您已提供布局,因此您无需指定app:actionViewClass

+0

谢谢你的回应:) –