2015-05-05 96 views
0

我是開發Android應用程序的初學者。我想在菜單上使用藍牙連接欄(操作欄?)。但是我不能讓藍牙狀態使用sw_Bt.setChecked() 切換這裏是我的onCreateOptionsMenu請幫助Switch菜單初始化

@Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     MenuInflater mInflater = getMenuInflater(); 
     mInflater.inflate(R.menu.menu_main, menu); 

     mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
     if (!mBluetoothAdapter.isEnabled()) { 
      menu.findItem(R.id.sw_BT).setChecked(false); 
     } else { 
      menu.findItem(R.id.sw_BT).setChecked(true) 
     } 
     return super.onCreateOptionsMenu(menu); 
//  return true; 
    } 

switch_bluetooth.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="match_parent" 
    tools:showIn="@layout/menu_main"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/bluetooth_connect" 
     android:textColor="@color/text" 
     android:textSize="15dp" 
     android:layout_gravity="center_vertical"/> 
    <Switch 
     android:id="@+id/sw_BT" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_vertical" 
     android:textOn="@string/connect" 
     android:textOff="@string/disconnect"/> 

</LinearLayout> 

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=".MainActivity"> 
    <item android:id="@+id/sw_BT" 
     android:title="" 
     app:showAsAction="always" 
     app:actionLayout="@layout/switch_bluetooth"/> 
</menu> 
+0

歡迎來到Stack Overflow。你能否描述你遇到的錯誤? 「我無法獲得藍牙狀態」不是很精確。 –

+0

好吧......我想讓我的布洛斯激活狀態在我的動作欄(開關)上,但它不工作setChecked()方法。它沒有運行時間或其他錯誤,但在應用程序切換不會改變,當我打開我的手機的藍牙 –

回答

0

你應使用onPrepareOptionsMenu代替onCreateOptionsMenu。 onCreateOptionsMenu被稱爲用於初始化菜單的。每次顯示菜單之前都會調用onPrepareOptionsMenu。

@覆蓋

public boolean onPrepareOptionsMenu(Menu menu) { 
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
    if (!mBluetoothAdapter.isEnabled()) { 
     menu.findItem(R.id.sw_BT).setChecked(false); 
    } else { 
     menu.findItem(R.id.sw_BT).setChecked(true) 
    } 
    return true; 
} 

還當過你的狀態更改來電invalidateOptionsMenu()再次調用onPrepareOptionsMenu。

+0

Thks爲響應,我添加onPrepareOptionsMenu(),但它沒有工作......有沒有錯誤,但開關沒有因血色狀態而改變(激活) –