//获取数据 private ArrayList<HashMap<String,Object>> getData(){ ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String,Object>>(); /**为动态数组添加数据*/ for(int i=0;i<500;i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("ItemTitle", "第"+i+"行"); map.put("ItemText", "这是第"+i+"行"); listItem.add(map); } return listItem; }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/txt_title_main" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> <TextView android:id="@+id/txt_title_sub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> <Button android:id="@+id/btn_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout>
然后就是BaseAdapter的编写
代码片断
//新建一个类继承BaseAdapter,实现视图与数据的绑定 private class MyAdapter extends BaseAdapter { private LayoutInflater mInflater; public MyAdapter(Context context) { this.mInflater = LayoutInflater.from(context); } @Override public int getCount() { return getData().size();//返回数组长度 } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView( int position, View convertView, ViewGroup parent) { //观察convertView随ListView滚动情况 View view; ViewHolder viewHolder; if(convertView == null){ view = mInflater.inflate(R.layout.item, null); TextView maintitle= (TextView) view.findViewById(R.id.txt_title_main); TextView subtitle= (TextView) view.findViewById(R.id.txt_title_sub); viewHolder = new ViewHolder(maintitle, subtitle); view.setTag(viewHolder); }else{ view = convertView ; viewHolder = (ViewHolder) view.getTag(); } /**设置TextView显示的内容,即我们存放在动态数组中的数据*/ viewHolder.maintitle.setText("by position" + position); viewHolder.subtitle.setText("by position" + position); return view; } } class ViewHolder { TextView maintitle; TextView subtitle; public ViewHolder(TextView maintitle, TextView subtitle){ this.maintitle = maintitle; this.subtitle = subtitle; } }
lv_show=(ListView) rootView.findViewById(R.id.lv_show); MyAdapter adapter=new MyAdapter(getActivity()); lv_show.setAdapter(adapter);