上一篇文章讲了异步任务帮助类的简单使用,这里使用异步任务帮助类模拟后台加载。
效果:
1.视图布局部分
模拟为动态为ListView加载资源,从效果图可以看到,最下方有一个”更多…“和一个旋转的加载控件。
1.1”更多…“按钮,背景使用系统样式
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/btn_loadmorecontacts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/list_selector_background"
android:text="更多..."
/>
1.2旋转的加载布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/progressBar"
android:text="正在加载…" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
2.java部分,使用继承自ListActivity的Activity,AsyncTask子类写为了内部类。
public class MyListView extends ListActivity implements OnClickListener {
private ArrayList<String> list;
private ViewSwitcher switcher;
private Button button;
private RelativeLayout progress;
String[] items = { "llall", "aaaaaa", "dasda", "xcxs", "asxzas",
"haahah", "lllllaa" }; //模拟的列表数据
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<String>();
switcher = new ViewSwitcher(this); //用于在两个View之间切换,每次只能显示一个View。
button = (Button) View.inflate(this, R.layout.button, null);//将"更多..."布局强行转换成按钮
button.setOnClickListener(this);
progress = (RelativeLayout) View.inflate(this, R.layout.progress, null);
//将两个view加入switcher
switcher.addView(button);
switcher.addView(progress);
getListView().addFooterView(switcher);//将view加入ListView底部
//加载模拟数据
for (String s : items) {
list.add(s);
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));//设置适配器
}
@Override
public void onClick(View v) {
switcher.showNext();//切换view
new DownloadItems().execute();//异步任务启动
}
private class DownloadItems extends AsyncTask<Object, Object, Object> {
@Override//后台处理
protected Object doInBackground(Object... params) {
try {
Thread.sleep(3000); //模拟加载的时间
} catch (InterruptedException e) {
e.printStackTrace();
}
//任务完成后添加数据
list.add("new one");
list.add("new two");
list.add("new three");
list.add("new four");
list.add("new five");
return null;
}
@Override//前台处理
protected void onPostExecute(Object result) {
super.onPostExecute(result);
switcher.showPrevious();//显示下一个view
setListAdapter(new ArrayAdapter<String>(MyListView.this,
android.R.layout.simple_list_item_1, list));//重新加载适配器
}
}
}