GridView是Android中常用的控件之一,用于展示數據的表格布局。
使用GridView需要以下步驟:
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3" />
GridView gridView = findViewById(R.id.gridView);
gridView.setAdapter(adapter);
public class GridAdapter extends BaseAdapter {
private Context context;
private List<String> data;
public GridAdapter(Context context, List<String> data) {
this.context = context;
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) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.item_grid, parent, false);
}
TextView textView = convertView.findViewById(R.id.textView);
textView.setText(data.get(position));
return convertView;
}
}
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp" />
以上是使用GridView的基本步驟,你可以根據實際需求進行修改和擴展。