我正在尝试使用切换按钮来切换设备中的蓝牙服务。但是当我第二次单击切换按钮时,活动总是崩溃。任何建议将不胜感激!谢谢!
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:text="Settings"
tools:ignore="HardcodedText" />
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:layout_weight="1.0"
android:textOn="Turn Off"
android:textOff="Turn On"
android:onClick="onToggleClicked"
tools:ignore="HardcodedText" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="Devices"
tools:ignore="HardcodedText" />
</LinearLayout>
<GridView
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3" >
</GridView>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 0;
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), "Device not supported!", Toast.LENGTH_LONG).show();
}
}
public void onToggleClicked(View v)
{
final ToggleButton toggle;
Boolean toggleStatus;
toggle = (ToggleButton)findViewById(R.id.toggleButton1);
toggleStatus = ((ToggleButton)v).isChecked();
if(toggleStatus)
{
toggle.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Enabling Bluetooth..", Toast.LENGTH_LONG).show();
}
}
});
}
else
{
toggle.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
Toast.makeText(getApplicationContext(), "Disabling Bluetooth..", Toast.LENGTH_LONG).show();
}
}
});
}
}