【问题标题】:Handler wont SetText on Button处理程序不会在按钮上设置文本
【发布时间】:2013-08-05 22:21:06
【问题描述】:

在我的应用程序中,我试图在我的Button purchaseButton 上简单地使用setText()。 我有一个警报对话框,它接受一个值并初始化一个 AsyncTask 以完成服务器调用以查找折扣。

一切正常,当我到达onPostExecute() 时。

onPostExecute():

protected void onPostExecute(String result) {
            Log.d(tag,"Result of POST: " + result);
            if(result != null){
                if(result.equals("NO")){
                    createAlert(1);

                }else{
                    result = result.replaceAll("YES", "");
                    String discount = result;
                    discountPrice = price - Double.parseDouble(discount);
                    Log.d(tag, "Discount price after pull:" + discountPrice);
                    //setPurchase("Purchase $" + String.valueOf(discountPrice));

                    new Thread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            Message msg = handler.obtainMessage();
                            msg.what = (int) discountPrice;
                            handler.sendMessage(msg);
                        }
                    }).start();

                }
            }

您可以看到我从 new Thread() 调用处理程序。这使我可以访问处理程序,但从不从处理程序设置按钮的文本。

处理方法:

final static Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            Log.d(tag, "entered handler");
            if(msg.what == discountPrice)
            {
                setPurchaseText(msg.what);
            }
        }
    };

setPurchaseText() 方法:

private static void setPurchaseText(int value){
        Log.d(tag, "Entered setPurchaseText");
        purchaseButton.setText("Purchase $" + String.valueOf(value));
    }

据我所知,这应该允许我从处理程序中设置文本。为什么它不设置文本,我怎样才能让它用我的字符串值设置文本?

非常感谢任何帮助!

【问题讨论】:

  • 你需要这个 Handler 干什么? onPostExecute() 已经在 UI 线程中运行。
  • 我已经尝试过 onPost 的 setText,这是我最初的命令。它也不会 setText.@SimonSays
  • 您不需要使用 String.valueOf(value) 只需执行此操作 "Purchase $"+value);这将连接整数值
  • 如果setText()onPostExecute() 中不起作用,那么问题就出在其他地方。您是否调试以查看您从doInBackground() 获得了正确的result?您是遇到错误还是文本没有改变?
  • 我确实最终让它在你之前的评论中起作用,它让我看起来更深入,并在 Double.parseDouble(String) 中找到了它。谢谢,它现在适用于PostExecute

标签: android button android-asynctask android-handler


【解决方案1】:

如果setText()onPostExecute() 中不起作用,那么您可能没有在 UI 线程上创建您的AsyncTaskAsyncTask 在您创建的线程上运行 onPostExecute()

同样,Handler 是在当前执行的Thread 上创建的。可能是您的 Handler 在后台线程上初始化。尝试使用final static Handler handler = new Handler(Looper.getMainLooper())。这确保处理程序附加到主线程。

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多