在Android GridView中显示多种类型,您需要创建一个自定义适配器(Adapter)来管理不同类型的数据
ItemA
和ItemB
。public class ItemA {
private String title;
public ItemA(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
public class ItemB {
private String description;
public ItemB(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
BaseAdapter
。在这个类中,您需要实现以下方法:getCount()
,getItem()
,getItemId()
和getView()
。public class CustomGridAdapter extends BaseAdapter {
private List<Object> items;
private LayoutInflater inflater;
public CustomGridAdapter(Context context, List<Object> items) {
inflater = LayoutInflater.from(context);
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.title = convertView.findViewById(R.id.text_title);
viewHolder.description = convertView.findViewById(R.id.text_description);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Object item = items.get(position);
if (item instanceof ItemA) {
viewHolder.title.setText(((ItemA) item).getTitle());
viewHolder.description.setVisibility(View.GONE);
} else if (item instanceof ItemB) {
viewHolder.title.setVisibility(View.GONE);
viewHolder.description.setText(((ItemB) item).getDescription());
}
return convertView;
}
static class ViewHolder {
TextView title;
TextView description;
}
}
grid_item.xml
中定义每种类型的视图。<?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="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/text_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/text_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:visibility="gone" />
</LinearLayout>
List<Object> items = new ArrayList<>();
items.add(new ItemA("Item A 1"));
items.add(new ItemB("Item B 1"));
items.add(new ItemA("Item A 2"));
items.add(new ItemB("Item B 2"));
CustomGridAdapter adapter = new CustomGridAdapter(this, items);
GridView gridView = findViewById(R.id.gridview);
gridView.setAdapter(adapter);
现在,您的GridView应该能够显示不同类型的元素,并根据其类型显示不同的布局。