所以我对android开发并不熟悉,很快就遇到了一个问题,我有一个想要启用/禁用设备的蓝牙和WiFi的视图,尽管两者都受控一个单独的开关。Android如何处理多个开关
因此,这里是我的看法是什么样的:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_connect"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="nl.neverdull.payleven.safeport.Connect">
<Switch
android:text="Bluetooth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:id="@+id/bluetooth_switch"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
tools:text="bluetooth"
android:contentDescription="Status of bluetooth"
android:textOn="@string/bluetooth_on"
android:textOff="@string/bluetooth_off" />
<Switch
android:text="Wifi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="25dp"
android:id="@+id/wifi_switch"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
tools:text="wifi" />
</RelativeLayout>
现在我已经有工作了蓝牙,这一点我是跟着
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
blueToothStatus();
wifiStatus();
}
public void blueToothStatus() {
Switch s = (Switch) findViewById(R.id.bluetooth_switch);
if (s != null) {
s.setOnCheckedChangeListener(this);
}
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Toast.makeText(this, "Bluetooth " + (isChecked ? "enabled" : "disabled"),
Toast.LENGTH_SHORT).show();
if(isChecked) {
mBluetoothAdapter.enable();
} else {
mBluetoothAdapter.disable();
}
}
现在,当我试图做同样的对于WiFi,它最终会使用相同的onCheckedChanged
函数,所以我的理想解决方案是如何让wifi使用它自己的onCheckedChanged函数?
截至目前我已经基本上为WIFI和蓝牙完全相同的代码,但它不会工作,因为双方最终会以相同的功能,这使得我的wifi开关改变蓝牙状态。
public void wifiStatus() {
Switch s = (Switch) findViewById(R.id.wifi_switch);
s.setOnCheckedChangeListener(this);//This goes to my onCheckedChanged
}
您可以定义onCheckedChanged监听器,例如强似“这个” – kingston
的其它选项建议立即进行删除是检查buttonView的id第一像 一个匿名类,如果(buttonView.getId() == bluetoothSwitchID) 其他 –