先声明:本人工作半年,是真的菜鸟,之前有做过2.3的Launcher,没有记录下来,感觉挺可惜的,现在老大叫我搞Setting,我觉得是得写得东西,记录下自己的工作。设备都还没到,现在只能看看代码,就先记录下看代码的收获吧。。
注意:Fragment是android3.0以上才支持的,3.0之前得导jar包,我在找Setting里面ListView的item的click事件时找了好久,因为之前关联的是2.3的源码,当我跳到PreferenceActivity类里面想看下Header类里,一直找不到(sb了),最后到官方的Reference上去找才想起来自己的源码关联的是2.3的(真的sb了...)。。。
Settings的包结构:
一、Setting的主界面
@Override public void onBuildHeaders(List<Header> headers) { loadHeadersFromResource(R.xml.settings_headers, headers); updateHeaderList(headers); mHeaders = headers; }
@Override public void setListAdapter(ListAdapter adapter) { if (mHeaders == null) { mHeaders = new ArrayList<Header>(); // When the saved state provides the list of headers, onBuildHeaders is not called // Copy the list of Headers from the adapter, preserving their order for (int i = 0; i < adapter.getCount(); i++) { mHeaders.add((Header) adapter.getItem(i)); } } // Ignore the adapter provided by PreferenceActivity and substitute ours instead super.setListAdapter(new HeaderAdapter(this, mHeaders)); }
private static class HeaderAdapter extends ArrayAdapter<Header> { //三种 类型的header static final int HEADER_TYPE_CATEGORY = 0;//分类 static final int HEADER_TYPE_NORMAL = 1;//一般的 static final int HEADER_TYPE_SWITCH = 2;//开关形式的 .... }
@Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); if (mAdapter != null) { Object item = mAdapter.getItem(position); if (item instanceof Header) onHeaderClick((Header) item, position); } }
public void onHeaderClick(Header header, int position) { if (header.fragment != null) { if (mSinglePane) { int titleRes = header.breadCrumbTitleRes; int shortTitleRes = header.breadCrumbShortTitleRes; if (titleRes == 0) { titleRes = header.titleRes; shortTitleRes = 0; } startWithFragment(header.fragment, header.fragmentArguments, null, 0, titleRes, shortTitleRes); } else { switchToHeader(header); } } else if (header.intent != null) { startActivity(header.intent); } }