java - Android - 将 View 从 Activity 传递到 AsyncTask 类

标签 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);
    }

}

我正在尝试从 MainActivity 执行 RemoteLoader 类。但是在 RemoteLoader 中包含一些需要膨胀 Main 布局的东西。

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

最佳答案

问题在于,例如,加载过程中方向发生变化, Activity 将重新创建, View 将不再有效。您冒着泄露 Activity 的风险。此外,您尝试写入的 View 将不再是可见的。

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

关于java - Android - 将 View 从 Activity 传递到 AsyncTask 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20795953/

相关文章:

java - Android 中模块化 AsyncTask 的设计模式

Java/JavaME : Quicker geometric vector addition

java - 如何直接从 Excel 工作表获取属性文件中包含键的值

java - Android: View 寻呼机中 fragment 之间的通信

java - android中的main或UI线程在哪里准备弯针?

Android——如何将应用程序的名称与标题栏分离?

android - android oncreate 是如何工作的?

java - 按 X 值对 List<Point> 进行排序的有效方法

java - 将对象持久保存到应用程序引擎时出现 "No API environment is registered for this thread"错误

android - 在 Plugin.execute() 中实例化 AsyncTask 时出现 ExceptionInInitializerError