天天看点

Loader之自定义AsyncTaskLoader<D>

Loader是android5.1新增加的api,兼容到android3.0系统。有两个子类CursorLoader和AsyncTaskLoader,CursorLoader主要是用访问系统Uri和数据库等,AsyncTaskLoader也可以完成cursorLoader的工作,异步loader一般自定义用来加载网络数据。

Loader有个最重要的特点就是能默认的缓存数据,已经加载过的不会重新加载,当然也可以人为的控制重新加载。Loader常用在横竖屏切换的时候数据不会第二次加载,节省资源和流量。

下面是横竖切换效果,数据只被加载一次

Loader之自定义AsyncTaskLoader<D>
//布局就是一个listview,模拟网络请求加载xml的string数组
<resources>
    <string name="app_name">LoaderDemo</string>
    <array name="testData" >
        <item>三国演义</item>
        <item>水浒传</item>
        <item>西游记</item>
        <item>浮生六记</item>
        <item>百草园</item>
        <item>三味书屋义</item>
        <item>霸王卸甲</item>
    </array>
</resources>
           
//这里是MainActivity的代码
public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private MyAdapter adapter;
    final String TAG = "=11 test 11=";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = ((ListView) findViewById(R.id.listView));
        adapter = new MyAdapter(this);
        listView.setAdapter(adapter);
        //初始化loader,第一个参数是loaderID,第二个是Boundle,第三个是回调
        getSupportLoaderManager().initLoader(, null, callbacks);
    }

    private LoaderManager.LoaderCallbacks<List<String>> callbacks = new LoaderManager.LoaderCallbacks<List<String>>() {
        @Override
        public Loader<List<String>> onCreateLoader(int id, Bundle args) {
            Log.i(TAG, "onCreateLoader: ==");//Loader创建的回调
            return new MyLoader(getApplicationContext());
        }

        @Override
        public void onLoadFinished(Loader<List<String>> loader, List<String> data) {
            Log.i(TAG, "onLoadFinished: ==");//数据加载完成回调
            adapter.swapData(data);
        }

        @Override
        public void onLoaderReset(Loader<List<String>> loader) {
            Log.i(TAG, "onLoaderReset:== ");
            //loader被销毁了,不再显示任何数据
            adapter.swapData(Collections.<String>emptyList());
        }
    };

    private class MyAdapter extends BaseAdapter {
        private Context mContext;
        private List<String> list = new ArrayList<>();

        MyAdapter(Context context) {
            mContext = context;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(android.R.layout.simple_expandable_list_item_1, listView, false);
                holder.textTest = (TextView) convertView.findViewById(android.R.id.text1);
                convertView.setTag(holder);
            }
            ViewHolder tag = (ViewHolder) convertView.getTag();
            tag.textTest.setText(list.get(position));
            return convertView;//还记得这个不,纯手撸
        }

        private void swapData(List<String> data) {
            list.clear();
            list.addAll(data);
            notifyDataSetChanged();
        }

        private class ViewHolder {
            TextView textTest;
        }
    }
}
           
//核心部分,自定义异步loader
/**
 * 自定义loader加载器<D>,为返回值类型
 * Created by Administrator on 2017/7/27.
 */

class MyLoader extends AsyncTaskLoader<List<String>> {
    private Context mContext;
    final String TAG = "=22test11=";
    //异步loader最核心的就是缓存数据
    List<String> cacheData;

    MyLoader(Context context) {
        super(context);
        mContext = context;
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==) {
                Toast.makeText(mContext,"子线程加载数据",Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    protected void onStartLoading() {
        if (cacheData == null) {
            //没有缓存数据,第一次加载
            forceLoad();
        }else {
            super.deliverResult(cacheData);
        }
        Log.i(TAG, "onStartLoading: ");
    }

    @Override
    public List<String> loadInBackground() {
        try {
            Thread.sleep();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        handler.sendEmptyMessage();
        String threadName = Thread.currentThread().getName();
        Log.i(TAG, "loadInBackground: " + threadName);
        String[] data = mContext.getResources().getStringArray(R.array.testData);
        return Arrays.asList(data);
    }

    @Override
    protected void onReset() {
        super.onReset();
        Log.i(TAG, "onReset: ");
    }

    @Override
    public void deliverResult(List<String> data) {
        //加载的数据进行缓存复用
        cacheData=data;
        super.deliverResult(cacheData);
    }
}