SimpleAdapter
SimpleAdapter其实一点也不simple的,因为我们需要自己去定义每个listitem的布局,如下:
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:padding="5dip" android:layout_width="match_parent" android:layout_height="match_parent">
<imageview android:id="@+id/imageView1" android:layout_width="80dip" android:layout_height="60dip" android:layout_alignparenttop="true" android:layout_alignparentleft="true" android:contentdescription="testing">
<textview android:id="@+id/tvTitle" android:layout_width="80dip" android:layout_height="wrap_content" android:layout_torightof="@+id/imageView1" android:layout_aligntop="@+id/imageView1">
<textview android:id="@+id/tvContent" android:layout_width="80dip" android:layout_height="wrap_content" android:layout_below="@+id/tvTitle" android:layout_torightof="@+id/imageView1" android:layout_alignbottom="@+id/imageView1">
我们定义了1个ImageView控件和两个TextView控件。 接下来我们看看MainActivity中的代码:
List<map<string, object="">> simpleList = new ArrayList<map<string, object="">>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initSimpleList();
ListView listView = (ListView)findViewById(R.id.listView1);
SimpleAdapter adapter = new SimpleAdapter(this, simpleList, R.layout.simpleadapter,
new String[] {"title","content","drawable"},
new int[] {R.id.tvTitle,R.id.tvContent,R.id.imageView1});
listView.setAdapter(adapter);
}
private void initSimpleList(){
String[] titles = {"title1", "title2", "title3","title4", "title5", "title6"};
String[] contents = {"content1", "content2", "content3","content4", "content5", "content6"};
int[] drawableIds = {R.drawable.computer,R.drawable.excel,R.drawable.game,
R.drawable.gc,R.drawable.network,R.drawable.pdf};
Map<string, object=""> map;
for(int i=0;i<6;i++){
map = new HashMap<string, object="">();
map.put("title", titles[i]);
map.put("content", contents[i]);
map.put("drawable", drawableIds[i]);
simpleList.add(map);
}
}</string,></string,></map<string,></map<string,>
从上面的代码中,我们可以看到,跟ArrayAdapter类似,也要先创建一个SimpleAdapter,其构造函数如下:
public SimpleAdapter(Context context, List<!--? extends Map<String, ?-->> data,
int resource, String[] from, int[] to) {
mData = data;
mResource = mDropDownResource = resource;
mFrom = from;
mTo = to;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
1)context,上下文 2)List> data,这是一个包含Map对象的list,也就是说,每个map对象都是每个item对应的内容。 3)resource,对应的就是这个item的layout,也就是我们上面自定义的布局。 4)from 和 to,这两个参数,其实就是做一个映射,将map中key对应的值,传给layout中每个对象的id。比如,我们上面在map中设置了title,那么这个title的值就是设给item布局对应的TextView(tvTitle),而其它的事情就由SimpleAdapter来帮我们操作了。
本文详细介绍了Android中SimpleAdapter的使用方法,包括自定义listitem布局、填充数据等过程,并提供了MainActivity中的示例代码。
926

被折叠的 条评论
为什么被折叠?



