这是在fragment中listview 以及适配器,还有toast方法的用法
ListView lv=view.findViewById(R.id.lv);
//先绑定组件
int[] image=new int[]{R.drawable.icon,R.drawable.icon,R.drawable.icon,R.drawable.icon,R.drawable.icon,R.drawable.icon
,R.drawable.icon,R.drawable.icon,R.drawable.icon,R.drawable.icon,R.drawable.icon};//这里是创建一个数组来保存显示的头像
String[] name=new String[]{"吾拉1","吾拉2","吾拉3","吾拉4","吾拉5","吾拉6","吾拉7","吾拉8","吾拉9","吾拉10","吾拉11"};//这里是创建一个数组来显示名字
List<Map<String,Object>> listItem=new ArrayList<>();
for(int i=0;i<image.length;i++){
Map<String,Object> map=new HashMap<>();
map.put("image",image[i]);
map.put("name",name[i]);
listItem.add(map);//上面是创建一个list<Map>来存头像和名字的信息
//相当于一个缓冲区
}
//下面是用simple adapter 适配器来把数据显示在指定的list view中
SimpleAdapter adapter=new SimpleAdapter(getActivity(),listItem,R.layout.item,new String[] {"image","name"},
new int[] {R.id.item_img,R.id.item_text});
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getActivity(),name[i],Toast.LENGTH_SHORT).show();
}//因为这是在fragment中写的,所以toast方法的第一个参数就不能用this了,得用getActivity();
});