以下是我的应用程序: 它执行蓝牙扫描,扫描功能在找到设备时会回调。 我想将特定按钮的文本从“搜索”更改为“连接”,一旦它找到一个特定的设备(它用设备名称识别)。如何在回调中更改按钮的文本? (Android)
但是,该按钮在回调的范围内无法访问。
有没有办法做到这一点?我认为这纯粹是一个范围问题,而我对这类事情几乎没有经验。
代码:
Context context;
context = this;
update_str = "";
Button ConnectButton = (Button) findViewById(R.id.Connect);
ConnectButton.setText("Waiting for device to be found");
Button ScanButton = (Button) findViewById(R.id.Scan);
ScanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btAdapter.startLeScan(leScanCallback);
}
});
BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
update_str = update_str.concat(" " + device.getName());
((TextView)findViewById (R.id.text)).setText (update_str);
nom_device = device.getName();
if (nom_device=="bill_gates"){
context.ConnectButton.setText(nom_device);
context.ConnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
BluetoothGatt bluetoothGatt = device.connectGatt(getApplicationContext(), false, context.btleGattCallback);
}
});
}
}
};
编译器错误日志:
C:\Code\Grizz\app\src\main\java\com\grizz\grizzmvp\MainActivity.java
Error:(84, 28) error: cannot find symbol variable ConnectButton
Error:(89, 117) error: cannot find symbol variable btleGattCallback
Error:(86, 28) error: cannot find symbol variable ConnectButton
Note: C:\Code\Grizz\app\src\main\java\com\grizz\grizzmvp\MainActivity.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Error:Execution failed for task ':app:compileDebugJava'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 1.381 secs
Information:4 errors
Information:0 warnings
Information:See complete output in console
您不必在每次想要更改某物时都按Id查找按钮。在第一行中声明它后,第二行可能只是:'ConnectButton.setText(Searching ...“);'。哦,你有多酷的名字! – Barthy
为什么你有一个Button叫做”ConnectButton “,其中ID为”连接“和另一个ID为”ConnectButton“的按钮?它也将有助于看到您的logcat /错误日志 – Barthy
这是意外的,并已按照您的建议更正 – Barth