项目中想要实现一个效果,就是我们显示用户不同景点下(个数事先不确定),不同的用户动态信息(带有图片,文字,个数事先不确定),所以,试图用listview中嵌套listview来实现,虽然效果不太美观,但还是尝试了一下,下面把基本思路和嵌套的运用记录一下。
1.文件说明:
MainActivity.java
activity_main.xml
item.xml
Item.java
subItem.xml
SubItem.java
(activity_main布局中运用到listview,引用item.xml布局定义,在item.xml中又运用到listview,引用subItem.xml布局定义,Item.java和SubItem.java是对应xml布局的类定义)
2.关键代码说明:
activity_main.xml中:
android:text="主界面布局"
android:id="@+id/list_view"
item.xml中:
android:text="一级listView布局"
android:id="@+id/sub_list_view"
Item.java中:
public class Item
{
private String text;
private private List subList;
public Item(String text, ListsubList)
{
this.text = text;
this.subList = subList;
}
public String getText()
{
return text;
}
public List getSubItemList()
{
return subList;
}
}
subItem.xml中:
android:text="二级listVIew布局"
SubItem.java中类似Item.java。
MainActivity中:
public class MainActivity implements OnCheckedChangeListener
{
private List itemList = new ArrayList();
protected void onCreate(Bundle savedInstanceState)
{
addItemListEle();
ItemAdapter itemAdapter = new ItemAdapter(MainActivity.this, R.layout.item, itemList);
ListView listview = (ListView)findViewById(R.id.list_view);
listview.setAdapter(itemAdapter);
}
public void addItemListEle()
{
for(int j =0 ; j < 3; j++)
{
List subItemList = new ArrayList();
for(int i =0 ; i < 3; i++)
{
subItemList.add(new SubItem("这是item"+j+"的第"+i+"个subItem",R.drawable...));
}
itemList.add(subItemList);
}
}
private class ItemAdapter extends ArrayAdapter
{
private int resourceId;
public ItemAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
resourceId = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Item item = getItem(position);// 获取当前项的Item实例
List subItemList = new ArrayList();
View view = LayoutInflater.from(getContext()).inflate(resourceId, null);
TextView itemText = (itemText)view.findViewById(R.id.itemtext);
ListView itemList = (ListView)view.findViewById(R.id.list_view);
//获得填充数据
itemText.setText(item.getText());
SubItemAdapter subItemAdapter = new SubItemAdapter(view.getContext, R.layout.subItem,subItemList);
itemList.setAdapter(subItemAdapter);
return view;
}
}
private class SubItemAdapter extends ArrayAdapter{
private int resourceId;
public SubItemAdapter(Context context, int resource,List objects) {
super(context, resource, objects);
resourceId = resource;
}
@Override
public View getView(int position, View arg1, ViewGroup arg2) {
SubItem subItem = getItem(position); //获得当前的SubItem实例
View view getLayoutInflater().inflate(ResouceId, null);
TextView subText = (TextView)findViewById(R.id.sub_text);
ImageView subImage = (ImageView)view1.findViewById(R.id.sub_image);
subImage.setImageResource(subItem.getImageId());
subText.setText(subItem.getText());
return view;
}
}
}
整个过程就是对外层list设置监听,外层list里的又对list进行监听,相互嵌套的过程就实现了。