【问题标题】:Refresh view after TextView.setText在 TextView.setText 之后刷新视图
【发布时间】:2018-02-15 16:08:16
【问题描述】:

我有一个已更新的 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?我做错了什么?

【问题讨论】:

  • 你确定onConnectionStateChange 被解雇了吗?在该方法中的某处放置一个断点,看看它是否命中?
  • 是的,它成功了。因为如果我最小化并重新打开 textView 更新的应用程序。
  • 我的意思是在应用程序运行时。
  • 是的,我现在已经对其进行了测试,并且它在应用程序运行时命中。
  • 为您的案例干杯(连接与否)。也许你会意识到这不是电视问题。

标签: android textview refresh


【解决方案1】:

你应该更新 (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);
    });
       

【讨论】:

  • 每当我需要更新视图时是否必须这样做?
  • 是的,所有视图都必须在 UI 线程上更新,因为 android 的 UI 框架是单线程的。如果您觉得这种方法过于冗长,您可以尝试其他方法,例如这里提到的stackoverflow.com/questions/12850143/…。您还可以使用反应式(RxJava/RxAndroid)或发布/订阅方法,并通过注释指定线程来处理接收到的事件。我非常喜欢 github.com/greenrobot/EventBus 的易用性。
猜你喜欢
  • 1970-01-01
  • 2023-03-11
  • 2016-05-07
  • 2011-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多