【问题标题】:How can I set the text for a textview from an AsyncTask activity?如何从 AsyncTask 活动设置文本视图的文本?
【发布时间】:2013-08-14 14:42:44
【问题描述】:

我有一个片段活动,其中包含一个文本视图和另一个扩展 AsyncTask 的类。现在我想使用onPostExecute(String result) 方法在我的片段活动中的文本视图中设置结果文本。

我该怎么做?我已经为接受上下文对象的 AsyncTask 类创建了一个自定义构造函数。我该如何使用它??

这就是我在 Fragment 活动中创建任务对象的方式:

String query = "someText";
Task task = new Task(this.getActivity());
task.execute(query);

这是我的任务类中的一个 sn-p:

public class Task extends AsyncTask<String, Void, String> {

    private Context context;

    public Task (Context context) {
        this.context = context;
    }

    protected void onPostExecute(String result) {
    super.onPostExecute(result);
    // ??? What comes here ???
    }
}

【问题讨论】:

  • 是你的 asynctask 一个你的活动类的内部类。 asynctask 不是一个活动
  • 不,它不是内部类。有问题吗?
  • @user2426316 请告诉我,这里有必要打电话吗?如果是这样,它有什么作用? (题外话)

标签: android android-asynctask textview


【解决方案1】:
TextView txt = (TextView)((Activity)context).findViewById(R.id.watheveryouwant);
txt.setText("blabla");

但是你应该传递一个Activity而不是一个Context,会更容易;-)

或者

    public Task (Context context, TextView t) {
        this.context = context;
        this.t = t;
    }
   super.onPostExecute(result);
        t.setText("BlahBlah")
    }

应该做的伎俩

【讨论】:

【解决方案2】:

您可以将TextView的实例作为参数传递给AsynkTast,并在onPostExecute中调用setText。

【讨论】:

    【解决方案3】:

    在您的情况下,只需以下操作即可:

    ((TextView)findViewById(R.id.xyz)).setText("abc");
    

    【讨论】:

      【解决方案4】:

      我从

      中选择了解决方案

      How do I return a boolean from AsyncTask?

      new Task(getActivity()).execute(query);
      

      AsyncTask的构造函数中

      TheInterface listener;
      public Task(Context context)
      {
        listener = (TheInterface) context; 
      }
      

      界面

      public interface TheInterface {
      
      public void theMethod(String result); // your result type
      
       }
      

      然后

      在你的 doInbackground 中返回结果。

      在你的 onPostExecute 中

      if (listener != null) 
      {
        listener.theMethod(result); // result is the String
        // result returned in doInbackground 
        // result of doInbackground computation is a parameter to onPostExecute 
      }
      

      在您的活动类或片段中实现接口

      public class ActivityName implements Task.TheInterface
      

      然后

      @Override
       public void theMethodString result) { 
          tv.setText(result); 
          // set the text to textview here with the result of background computation
          // remember to declare textview as a class member.
       }
      

      编辑:

      您还缺少onPostExecute 的@Override 注释

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-01
        • 2023-03-16
        • 2016-02-28
        相关资源
        最近更新 更多