2014-09-10 58 views
0

我遵循以下鏈接中介紹的過程,但出於某種原因,切換從不顯示。我改變了可見性以匹配我的應用程序名稱空間,正如其他線程中所建議的那樣無濟於事。如果我嘗試添加圖標或常規按鈕,該過程正常工作。Android - 添加切換到操作欄不工作

非常感謝。

我與Android 4.4.4運行它在Nexus 4

How to add a switch to android action bar?

這裏是我當前的XML內容。

/menu/main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    tools:context="com.example.testapp.MainActivity" > 

    <item 
     android:id="@+id/myswitch" 
     android:title="" 
     app:showAsAction="always" 
     android:actionLayout="@layout/switch_layout" 
    /> 
</menu> 

/layout/switch_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 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="" /> 
</LinearLayout> 
+0

您是否嘗試使用'RelativeLayout'而不是'LinearLayout'? – 2014-09-10 18:24:57

+0

這裏是一個不同的方法將開關添加到[操作欄](http://stackoverflow.com/q/15338471/3326331) – 2014-09-10 18:26:52

+0

@Sash_KP - 是的。首先,我從鏈接中嘗試了RelativeLayout。 – Andre 2014-09-10 18:31:54

回答

0

好了,我終於找到了一種適合我的工作。

我創建了一個佈局文件:我MainActivity.java

protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     ActionBar mActionBar = getActionBar(); 

     LayoutInflater mInflater = LayoutInflater.from(this); 

     View mCustomView = mInflater.inflate(R.layout.test_layout, null); 

     mActionBar.setCustomView(mCustomView); 
     mActionBar.setDisplayShowCustomEnabled(true); 
} 

BOOOMMM /layout/text_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    > <!-- android:layout_height="50dp" --> 

    <Switch 
     android:id="@+id/switchForActionBar" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentRight="true" 
     android:layout_centerVertical="true" 
     /> 
</RelativeLayout> 

然後,你去那裏。

令人印象深刻的是,Android有時候簡單的事情會如此複雜。

感謝您的建議。