Android - 将View从Activity传递到AsyncTask类

时间:2013-12-27 06:27:46

标签: java android android-asynctask

MainActivity.java:

private class NetCheck extends AsyncTask<String, Void, Boolean> {
    @Override
    protected Boolean doInBackground(String... args) {
        return cd.isConnectingToInternet();
    }

    protected void onPostExecute(Boolean th) {
        if (th == true) {
            new RemoteLoader(MainActivity.this).execute();
        }
    }
}

RemoteLoader.java:

public class RemoteLoader extends AsyncTask<Void, Void, Void>{
    private View view;

    public RemoteLoader(View context){
        this.view = view;
    }

    @Override
    protected Void doInBackground(Void... Pages) {
             // do in bg
    }

    @Override
    protected void onPostExecute(Void result) {
        // Set title into TextView
        TextView txttitle = (TextView) view.findViewById(R.id.txtProtip);
        txttitle.setText(protip);
    }

}

我正在尝试从RemoteLoader执行MainActivity课程。但是在RemoteLoader中包含需要扩展Main布局的东西。

在这种情况下,如何将布局从MainActivity传递到RemoteLoader?

4 个答案:

答案 0 :(得分:3)

这个问题是在例如加载过程中的方向更改将重新创建活动,并且视图将不再有效。您冒泄漏活动的风险。此外,您尝试写入的视图将不再是可见的视图。

查看Robospice文档以了解基本问题: https://github.com/octo-online/robospice/wiki/Understand-the-basics-of-RoboSpice-in-30-seconds 这是关于Android的一个棘手的部分。

答案 1 :(得分:2)

将Activity传递给RemoteLoader而不是View,如下所示

private WeakReference<Activity> activity;

public RemoteLoader(Activity context){
    this.activity = new WeakReference<Activity>(context);
}

更新:使用弱引用来防止可能的内存泄漏。

答案 2 :(得分:2)

将此代码用于RemoteLoader: -

public class RemoteLoader extends AsyncTask<Void, Void, Void>{

LayoutInflater inflater;
int layoutResId;

public RemoteLoader(View context,int layoutResId){
    this.view = view;
    inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.layoutResId = layoutResId;
}

@Override
protected Void doInBackground(Void... Pages) {
         // do in bg
}

@Override
protected void onPostExecute(Void result) {
    // Set title into TextView
    View yourLayout = inflater.inflate(layoutResId, null);
    TextView txttitle = (TextView) yourLayout.findViewById(R.id.txtProtip);
    txttitle.setText(protip);
}

}

答案 3 :(得分:0)

您可以通过构造函数

将TextView引用传递给异步任务类
public class RemoteLoader extends AsyncTask<Void, Void, Void>{

    TextView txtTitle;

    public RemoteLoader(TextView txtTitle){
        this.txtTitle = txtTitle;
    }

    @Override
    protected Void doInBackground(Void... Pages) {
             // do in bg
    }

    @Override
    protected void onPostExecute(Void result) {
        // Set title into TextView
        txttitle.setText(protip);
    }

}
主活动中的

执行与follwos

相同的异步任务
TextView txttitle = (TextView) view.findViewById(R.id.txtProtip);
new RemoteLoader(txttitle).execute();

如果要从另一个异步任务执行此异步任务,则通过MainActivity中的textView引用传递