在 TextView.setText 之后刷新视图

Lec*_*ico 1 android refresh textview

我有一个已更新的 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;
                }
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要刷新那个 TextView 吗?我做错了什么吗?

Cri*_*ert 6

您应该像这样更新主(ui)线程中TextView

    runOnUiThread(new Runnable() {
        public void run() {
            state.setText("Connected = False");
            state.setTextColor(Color.RED);
        }
    });
Run Code Online (Sandbox Code Playgroud)

或者,如果您的项目配置为支持 java 8,您可以更简洁地编写它

    runOnUiThread(() -> {
       state.setText("Connected = False");
       state.setTextColor(Color.RED);
    });
       
Run Code Online (Sandbox Code Playgroud)