【问题标题】:Android : TextView setText only works at the first timeAndroid : TextView setText 只在第一次工作
【发布时间】:2017-02-08 12:26:55
【问题描述】:

每次进入主活动,下面的代码都会被执行并正常工作(这意味着indexStatus.setText(msg.obj.toString());总是显示最新的消息)。

但是如果我按back 按钮切换出去,然后在同一个屏幕中切换(reBuildIndex 将再次运行),Log.d(TAG, msg.obj.toString()); 工作正常,打印出最新消息,但indexStatus.setText 没有' t 工作,最新的 msg 没有按我预期的那样显示。

这里发生了什么?有什么建议吗?

void rebuildIndex(boolean reCreate) {
    final TextView indexStatus = (TextView) this.findViewById(R.id.index_status);
    indexStatus.setVisibility(View.INVISIBLE);
    indexStatus.setText(R.string.rebuild_index_progress_title);

    final Handler statusHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
      @Override
      public boolean handleMessage(Message msg) {
        if (msg.obj == null) {
          indexStatus.setVisibility(View.GONE);
        } else if (msg.obj.equals("show")) { // TODO quick demo, shouldn't use literal text.
          indexStatus.setVisibility(View.VISIBLE);
        } else {
          Log.d(TAG, msg.obj.toString());
          if (indexStatus.getVisibility() != View.VISIBLE) {
            indexStatus.setVisibility(View.VISIBLE);
          }
          indexStatus.setText(msg.obj.toString());
          indexStatus.invalidate();
        }
        return false;
      }
    });

    Indexer.rebuildIndexIfNecessary(statusHandler, reCreate);
  }

更新:

我在第三个条件setText之后添加了indexStatus.invalidate();,也不起作用。

更新: 原帖有错误消息,我说按home,但实际上是back 切换出去。 home 按钮切换出/入工作正常。

更新: 试图将处理程序放置为全局变量,但没有奏效。现在我禁用了back 事件。

【问题讨论】:

  • 这很有趣。我可以知道当它没有按预期运行时你看到了什么(消息)吗?
  • 你能提供更多关于rebuildIndex() 再次被调用的信息吗?是来自onResume() 吗?是什么实际触发了该方法以及什么触发了HandlerhandleMessage()
  • rebuildIndex是从activity的onStart调用的,message是一个普通的字面量String
  • @LightYearsBehind 什么都没有显示,似乎视图根本不可见
  • 听起来像“else”的情况没有被调用,但你说Log.d(...) 有效。我假设你没有在其他地方调用Log.d(...)

标签: android


【解决方案1】:

如果需要在这部分代码中始终设置TextView可见:

if (indexStatus.getVisibility() != View.VISIBLE) {
    indexStatus.setVisibility(View.VISIBLE);
}

然后删除if 部分。

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多