加载器的作用很明显了,和Fragmnet配合起来使用,项目整体的结构如下图

image 

第二部分,贴出所有代码:

1.Friend.java

package com.zhai.loader;

public class Friend {

    public Friend(String string) {
        // TODO Auto-generated constructor stub

        this.name = string;
    }

    String name;
}

2. FriendActivity.java

package com.zhai.loader;

import java.util.List;

import com.zhai.loader.LoaderCustom.AppEntry;
import com.zhai.loader.LoaderCustom.AppListAdapter;
import com.zhai.loader.LoaderCustom.AppListFragment;
import com.zhai.loader.LoaderCustom.AppListLoader;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.Loader;
import android.os.Bundle;

public class FriendActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 第一步
        FragmentManager fm = getFragmentManager();
        // 如果是空的话创建,如果不为空的话不再创建
        if (fm.findFragmentById(android.R.id.content) == null) {
            FriendListFragment list = new FriendListFragment();
            fm.beginTransaction().add(android.R.id.content, list).commit();
        }
    }

    public static class FriendListFragment extends ListFragment implements
            LoaderManager.LoaderCallbacks<List<Friend>> {

        FriendListAdapter mAdapter;

        // 必须手机添加的
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            setEmptyText("没有好友");
            setHasOptionsMenu(true);
            // Create an empty adapter we will use to display the loaded data.
            mAdapter = new FriendListAdapter(getActivity());
            setListAdapter(mAdapter);
            // Start out with a progress indicator.
            setListShown(false);

            // Prepare the loader. Either re-connect with an existing one,
            // or start a new one.
            getLoaderManager().initLoader(0, null, this);
        }

        // 第一个–ok
        @Override
        public Loader<List<Friend>> onCreateLoader(int id, Bundle args) {
            // TODO Auto-generated method stub
            return new FriendListLoader(getActivity());
        }

        @Override
        public void onLoadFinished(Loader<List<Friend>> loader,
                List<Friend> data) {
            // TODO Auto-generated method stub
            mAdapter.setData(data);

            // The list should now be shown.
            if (isResumed()) {
                setListShown(true);
            } else {
                setListShownNoAnimation(true);
            }

        }

        @Override
        public void onLoaderReset(Loader<List<Friend>> arg0) {
            // TODO Auto-generated method stub
            mAdapter.setData(null);
        }

        // 继承三个方法

    }
}

3.FriendListAdapter.java

package com.zhai.loader;

import java.util.List;

import com.example.loader.R;
import com.zhai.loader.LoaderCustom.AppEntry;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class FriendListAdapter extends ArrayAdapter<Friend> {
    private final LayoutInflater mInflater;

    public FriendListAdapter(Context context) {
        super(context, android.R.layout.simple_list_item_2);
        mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void setData(List<Friend> data) {
        clear();
        if (data != null) {
            addAll(data);
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;

        if (convertView == null) {
            view = mInflater.inflate(R.layout.list_item_icon_text, parent,
                    false);
        } else {
            view = convertView;
        }

        Friend item = getItem(position);
        ((TextView) view.findViewById(R.id.text)).setText(item.name);

        return view;
    }
}

4.FriendListLoader.java

package com.zhai.loader;

import java.util.ArrayList;
import java.util.List;

import com.zhai.loader.LoaderCustom.PackageIntentReceiver;

import android.content.AsyncTaskLoader;
import android.content.Context;

public class FriendListLoader extends AsyncTaskLoader<List<Friend>> {

    List<Friend> friendlist;

    // 第一步,添加构造器
    public FriendListLoader(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    // 第二步,在后台创建的数据
    @Override
    public List<Friend> loadInBackground() {
        List<Friend> _friendList = new ArrayList<Friend>();
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            _friendList.add(new Friend("zhai" + i));
        }
        // 花时间创建的朋友列表
        return _friendList;
    }

    @Override
    protected void onStartLoading() {
        if (friendlist != null) {
            // If we currently have a result available, deliver it
            // immediately.
            deliverResult(friendlist);
        }

        // Has something interesting in the configuration changed since we
        // last built the app list?

        if (takeContentChanged() || friendlist == null) {
            // If the data has changed since the last time it was loaded
            // or is not currently available, start a load.
            forceLoad();
        }
    }

    @Override
    protected void onStopLoading() {
        // Attempt to cancel the current load task if possible.
        cancelLoad();
    }

    @Override
    public void deliverResult(List<Friend> _friendList) {
        if (isReset()) {
            // An async query came in while the loader is stopped. We
            // don’t need the result.
            if (_friendList != null) {
                onReleaseResources(_friendList);
            }
        }
        List<Friend> oldApps = _friendList;
        friendlist = _friendList;

        if (isStarted()) {
            // If the Loader is currently started, we can immediately
            // deliver its results.
            super.deliverResult(_friendList);
        }

        // At this point we can release the resources associated with
        // ‘oldApps’ if needed; now that the new result is delivered we
        // know that it is no longer in use.
        if (oldApps != null) {
            onReleaseResources(oldApps);
        }
    }

    @Override
    protected void onReset() {
        super.onReset();

        // Ensure the loader is stopped
        onStopLoading();

        // At this point we can release the resources associated with ‘apps’
        // if needed.
        if (friendlist != null) {
            onReleaseResources(friendlist);
            friendlist = null;
        }

    }

    private void onReleaseResources(List<Friend> _friendList) {
        // TODO Auto-generated method stub

    }
}

5. manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.loader"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/head"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.zhai.loader.FriendActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.zhai.loader.LoaderCustom"
            android:label="@string/app_name" >
            <intent-filter>
            </intent-filter>
        </activity>
    </application>

</manifest>

6. list_item_icon_test.xml

<?xml version="1.0" encoding="utf-8"?>
<!–
     Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
–>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="48dip"
        android:layout_height="48dip"
        android:src="@drawable/head" />

    <TextView
        android:id="@+id/text"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="1.0" />

</LinearLayout>

第三部分,结果截图:

device-2012-11-16-160900 device-2012-11-16-160908

第四部分, 本实例源代码下载

本地下载地址: 点击我下载.zip