【问题标题】:Handler postDelayed not able to update UI处理程序 postDelayed 无法更新 UI
【发布时间】:2014-02-21 10:07:47
【问题描述】:

大家好,我正在尝试在短暂延迟后更新 UI,为此我正在使用处理程序的 postdelayed 方法。以下代码最初将我的 textview 文本设置为“正在处理”,并且处理程序的可运行文件中包含的代码被执行但不更新 UI?请注意,这是在 Fragment 中完成的

TextView progressText=(TextView)parent.findViewById(R.id.inProgressText);
progressText.setText("Processing");

getActivity().getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        TextView progressText=(TextView)parent.findViewById(R.id.inProgressText);
        progressText.setText("Request completed");              
    }
}, 3000);

感谢您的帮助

【问题讨论】:

  • 该代码有什么问题?
  • @pskink 此代码最初将我的 textview 文本设置为“处理中”,但处理程序可运行中包含的代码被执行但不更新 UI?
  • 会不会是你一次使用parent.findViewById(R.id.inProgressText);,下次你使用uiObject.findViewById(R.id.inProgressText);
  • @Tom Hart 抱歉,这只是一个错字。我刚刚更新了我的帖子

标签: android android-fragments android-handler


【解决方案1】:

使用此代码

public class MainActivity extends Activity {
TextView progressText = null;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.activity_main, container, false);

    progressText = (TextView) rootView.findViewById(R.id.inProgressText);
    progressText.setText("Processing");
    progressText.postDelayed(new Runnable() {
        @Override
        public void run() {
            progressText.setText("Request completed");
        }
    }, 3000);
       return rootView;
}
}

【讨论】:

  • 抱歉 Rajan 没用,请注意这段代码 sn-p 在片段中
  • 但是你可以把它转换成片段
  • 是的,我已经在 Fragment 中实现了相同的功能,但它不起作用。
【解决方案2】:

请尝试这种方式:我签入了 Fragment,它运行良好。

View parent= inflater.inflate(R.layout.your_fragement, container, false);
TextView progressText=(TextView)parent.findViewById(R.id.inProgressText);
progressText.setText("Processing");

            progressText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    progressText.setText("Request completed");
                }
            }, 3000);

【讨论】:

    【解决方案3】:

    改变

    getActivity().getMainLooper()).postDelayed(new Runnable()
    

    到:

    final Handler handler = new Handler();
    

    然后

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            final TextView progressText=(TextView)findViewById(R.id.inProgressText);
            progressText.setText("Request completed");              
        }
    }, 3000);
    

    【讨论】:

    • 一开始是一样的,但没用,后来把我的代码改成了你现在看到的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2015-04-23
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多