Android GridView Tutorial: Complete Guide
GridView is a commonly used layout widget in Android that displays multiple items in a grid layout. Below are the steps for using GridView:
- Add a GridView control to the XML layout file.
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="2"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"/>
- In the Activity, obtain an instance of the GridView control and set the adapter.
GridView gridView = findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this)); // MyAdapter为自定义的适配器类
- Create a custom adapter class called MyAdapter, which extends BaseAdapter and implements the following methods:
@Override
public int getCount() {
// 返回GridView中项目的数量
}
@Override
public Object getItem(int position) {
// 返回指定位置的项目对象
}
@Override
public long getItemId(int position) {
// 返回指定位置的项目ID
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 返回指定位置的项目视图
}
- In the getView method of MyAdapter, we can reuse existing views by using the convertView parameter to improve performance. You can use LayoutInflater to load custom item layouts and set different data for each item.
By following the above steps, you can now use the GridView control in an Android application to display multiple items.