在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和布局文件进行定制化。