Loader和Fragment使用示例代码
2011-03-19 11:57:23 来源:本站整理Loader和Fragment都是Android 3.0的新特性,有关Fragment相关的内容已经用了多个篇幅介绍,而Loader相关的大家可以通过 LoaderManager - Android 3.0新特性 一文了解Loader的作用和结构,下面就以一个简单的工程示例代码了解下Loader。
public class FragmentListCursorLoader extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getFragmentManager(); //获取FragmentManager这个服务实例
if (fm.findFragmentById(android.R.id.content) == null) { //这个资源是android内部的布局,注意是android.R
CursorLoaderListFragment list = new CursorLoaderListFragment();
fm.beginTransaction().add(android.R.id.content, list).commit();
}
}
public static class CursorLoaderListFragment extends ListFragment
implements OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> {
SimpleCursorAdapter mAdapter; //这里使用简单cursor适配器绑定数据库
String mCurFilter;
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText("No phone numbers");
setHasOptionsMenu(true); //显示actionbar,如果不明白看android123以前的文章
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2, null,
new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
new int[] { android.R.id.text1, android.R.id.text2 }, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuItem item = menu.add("Search");
item.setIcon(android.R.drawable.ic_menu_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
SearchView sv = new SearchView(getActivity());
sv.setOnQueryTextListener(this);
item.setActionView(sv);
}
public boolean onQueryTextChange(String newText) {
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
getLoaderManager().restartLoader(0, null, this);
return true;
}
@Override public boolean onQueryTextSubmit(String query) {
return true;
}
@Override public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentComplexList", "Item clicked: " + id);
}
更多精彩
赞助商链接