我是開發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>
歡迎來到Stack Overflow。你能否描述你遇到的錯誤? 「我無法獲得藍牙狀態」不是很精確。 –
好吧......我想讓我的布洛斯激活狀態在我的動作欄(開關)上,但它不工作setChecked()方法。它沒有運行時間或其他錯誤,但在應用程序切換不會改變,當我打開我的手機的藍牙 –