Fragment中使用listview

昨天按照在activity中的方法使用listview结果一直报错,今天参考了某高人博客后发现fragment中使用listview和activity中是不一样的。
(参考博客:http://qurtyy.blog.163.com/blog/static/574436812013112543231523/)


在Fragment的布局中必须包含id "@android:id/list"(在代码中则是list)的Listview。

fragement要extend  ListFragment而不是fragment。

只能使用SimpleAdapter或者SimpleCursorAdapter作为适配器。

直接使用ListFragment的setListAdapter()来设置适配器。


上代码


fragement部分:

me.xml:




    
    



listitem部分:
me_function_item.xml:



    

    



fragement.java部分:
注意oncreate和oncreateview的区别

public class MeFragment extends ListFragment {
	private ListView list;
	private SimpleAdapter adapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.me, container, false);
		list = (ListView) view.findViewById(android.R.id.list);
		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		String[] listItem = { "a", "b", "c", "d", "e" };
		int[] iconItem = { R.drawable.ic_launcher, R.drawable.ic_launcher,
				R.drawable.ic_launcher, R.drawable.ic_launcher,
				R.drawable.ic_launcher };
		adapter = new SimpleAdapter(getActivity(), getData(listItem, iconItem),
				R.layout.me_function_item, new String[] { "name", "icon" },
				new int[] { R.id.functionName, R.id.functionIcon });
		setListAdapter(adapter);

	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

	}

	private List> getData(String[] strs, int[] icon) {
		List> list = new ArrayList>();

		for (int i = 0; i < 5; i++) {
			Map map = new HashMap();
			map.put("name", strs[i]);
			map.put("icon", icon[i]);
			list.add(map);

		}

		return list;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

	}

}


 
   

你可能感兴趣的:(android)