在Android中自定義DataGridView,可以通過自定義Adapter來實現。以下是實現步驟:
public class CustomAdapter extends BaseAdapter {
private Context context;
private List<MyData> dataList;
public CustomAdapter(Context context, List<MyData> dataList) {
this.context = context;
this.dataList = dataList;
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.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) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_row, parent, false);
}
TextView textView1 = convertView.findViewById(R.id.textView1);
TextView textView2 = convertView.findViewById(R.id.textView2);
MyData data = dataList.get(position);
textView1.setText(data.getData1());
textView2.setText(data.getData2());
return convertView;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:id="@+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity {
private List<MyData> dataList;
private CustomAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = findViewById(R.id.gridView);
// 初始化數據
initData();
// 創建Adapter
adapter = new CustomAdapter(this, dataList);
// 設置Adapter
gridView.setAdapter(adapter);
}
private void initData() {
dataList = new ArrayList<>();
dataList.add(new MyData("Data1-1", "Data1-2"));
dataList.add(new MyData("Data2-1", "Data2-2"));
dataList.add(new MyData("Data3-1", "Data3-2"));
}
}
通過以上步驟,就可以在Android中自定義GridView或ListView,并實現類似DataGridView的效果。可以根據實際需求對Adapter和布局文件進行定制化。