以下是我的應用程序: 它執行藍牙掃描,掃描功能在找到設備時會回調。 我想將特定按鈕的文本從「搜索」更改爲「連接」,一旦它找到一個特定的設備(它用設備名稱識別)。如何在回調中更改按鈕的文本? (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