在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應該能夠顯示不同類型的元素,并根據其類型顯示不同的布局。