在 Android 中,沒有名為 DataGrid 的內置控件
首先,將 RecyclerView 依賴項添加到項目的 build.gradle 文件中:
dependencies {
implementation 'com.android.support:recyclerview-v7:28.0.0'
}
然后,在布局文件(例如:activity_main.xml)中添加 RecyclerView:
android:id="@+id/data_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
接下來,創建一個表示單個網格項的 XML 布局文件(例如:grid_item.xml):
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item Text"/>
</LinearLayout>
創建一個自定義適配器(例如:MyGridAdapter.java):
public class MyGridAdapter extends RecyclerView.Adapter<MyGridAdapter.ViewHolder> {
private List<String> dataList;
public MyGridAdapter(List<String> dataList) {
this.dataList = dataList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(dataList.get(position));
}
@Override
public int getItemCount() {
return dataList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
}
}
}
最后,在 Activity 或 Fragment 中設置 RecyclerView:
RecyclerView recyclerView = findViewById(R.id.data_grid);
recyclerView.setLayoutManager(new GridLayoutManager(this, 2)); // 這里的 2 表示列數
List<String> dataList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
dataList.add("Item " + i);
}
MyGridAdapter adapter = new MyGridAdapter(dataList);
recyclerView.setAdapter(adapter);
在布局文件(例如:activity_main.xml)中添加 TableLayout:
android:id="@+id/data_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*"
android:shrinkColumns="*"/>
在 Activity 或 Fragment 中動態添加行和列:
TableLayout tableLayout = findViewById(R.id.data_grid);
for (int i = 0; i < 5; i++) {
TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
for (int j = 0; j < 2; j++) {
TextView textView = new TextView(this);
textView.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
textView.setText("Cell " + i + "," + j);
tableRow.addView(textView);
}
tableLayout.addView(tableRow);
}
這樣,您就可以在 Android 項目中使用類似 DataGrid 的功能了。建議使用 RecyclerView,因為它具有更好的性能和靈活性。