要實現自定義樣式的GridView,可以通過以下步驟實現:
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/customGridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:padding="10dp"
android:background="@color/white"
/>
GridView customGridView = findViewById(R.id.customGridView);
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private List<String> mData;
public CustomAdapter(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) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_grid_item, parent, false);
}
TextView textView = convertView.findViewById(R.id.textView);
textView.setText(mData.get(position));
// 自定義樣式
textView.setTextColor(Color.RED);
textView.setBackgroundColor(Color.LIGHT_GRAY);
return convertView;
}
}
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="@android:color/black"
android:background="@android:color/white"
/>
CustomAdapter customAdapter = new CustomAdapter(this, dataList);
customGridView.setAdapter(customAdapter);
通過以上步驟,你可以實現一個自定義樣式的GridView。你可以根據需求修改自定義的布局文件和樣式來達到你想要的效果。