在Android中,GridView是一種可用于顯示數據的布局控件,它以網格的形式展示數據項。GridView通過Adapter來提供數據,并自動根據列數和行數來排列和展示數據項。
GridView的用法如下:
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3" // 設置每行顯示的列數
android:verticalSpacing="10dp" // 設置每行之間的垂直間距
android:horizontalSpacing="10dp" // 設置每列之間的水平間距
android:padding="10dp" // 設置GridView的內邊距
android:stretchMode="columnWidth" // 設置列寬自適應
android:gravity="center" // 設置內容居中顯示
/>
public class GridAdapter extends BaseAdapter {
private Context mContext;
private List<String> mData;
public GridAdapter(Context context, List<String> data) {
mContext = context;
mData = data;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.grid_item, parent, false);
holder = new ViewHolder();
holder.textView = convertView.findViewById(R.id.textview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
private static class ViewHolder {
TextView textView;
}
}
public class MainActivity extends AppCompatActivity {
private GridView mGridView;
private List<String> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGridView = findViewById(R.id.gridview);
mData = new ArrayList<>();
// 添加數據項
mData.add("Item 1");
mData.add("Item 2");
mData.add("Item 3");
mData.add("Item 4");
mData.add("Item 5");
GridAdapter adapter = new GridAdapter(this, mData);
mGridView.setAdapter(adapter);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 處理點擊事件
}
});
}
}
以上就是使用GridView控件的基本用法。可以根據實際需求自定義Adapter和布局文件,以展示不同類型的數據項。