要在Android GridView中顯示數據,可以使用以下方法:
以下是一個簡單示例代碼:
List<String> data = new ArrayList<>();
data.add("Item 1");
data.add("Item 2");
data.add("Item 3");
public class MyAdapter extends BaseAdapter {
private List<String> data;
public MyAdapter(List<String> data) {
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 獲取或創建視圖
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.grid_item, parent, false);
}
// 設置數據
TextView textView = view.findViewById(R.id.text_view);
textView.setText(data.get(position));
return view;
}
}
<GridView
android:id="@+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:horizontalSpacing="8dp"
android:verticalSpacing="8dp"
android:padding="8dp"/>
GridView gridView = findViewById(R.id.grid_view);
MyAdapter adapter = new MyAdapter(data);
gridView.setAdapter(adapter);
這樣就可以在GridView中顯示數據了。需要注意的是,還可以自定義每個項的布局,例如使用ImageView和TextView顯示更復雜的數據。