TextView.setText 后刷新视图
Refresh view after TextView.setText
我有一个已更新的 TextView,但在我最小化并重新打开应用程序之前我看不到刷新。这是执行该操作的代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bleAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();
Set<BluetoothDevice> pairedDevices = bleAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
device.connectGatt(this, true, new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
TextView state;
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
state = (TextView)findViewById(R.id.state);
state.setText("Connected = True");
state.setTextColor(Color.GREEN);
break;
case BluetoothProfile.STATE_DISCONNECTED:
state = (TextView)findViewById(R.id.state);
state.setText("Connected = False");
state.setTextColor(Color.RED);
break;
}
}
});
}
}
刷新 TextView 需要什么?我做错了什么吗?
您应该在主 (ui) 线程 中更新 TextView,像这样
runOnUiThread(new Runnable() {
public void run() {
state.setText("Connected = False");
state.setTextColor(Color.RED);
}
});
或者如果你的项目是configured to support java 8你可以写得更简洁
runOnUiThread(() -> {
state.setText("Connected = False");
state.setTextColor(Color.RED);
});
我有一个已更新的 TextView,但在我最小化并重新打开应用程序之前我看不到刷新。这是执行该操作的代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bleAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();
Set<BluetoothDevice> pairedDevices = bleAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
device.connectGatt(this, true, new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
TextView state;
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
state = (TextView)findViewById(R.id.state);
state.setText("Connected = True");
state.setTextColor(Color.GREEN);
break;
case BluetoothProfile.STATE_DISCONNECTED:
state = (TextView)findViewById(R.id.state);
state.setText("Connected = False");
state.setTextColor(Color.RED);
break;
}
}
});
}
}
刷新 TextView 需要什么?我做错了什么吗?
您应该在主 (ui) 线程 中更新 TextView,像这样
runOnUiThread(new Runnable() {
public void run() {
state.setText("Connected = False");
state.setTextColor(Color.RED);
}
});
或者如果你的项目是configured to support java 8你可以写得更简洁
runOnUiThread(() -> {
state.setText("Connected = False");
state.setTextColor(Color.RED);
});