Android中可以使用RecyclerView和GridLayoutManager來實(shí)現(xiàn)復(fù)雜表格控件。下面是一個(gè)簡單的示例代碼:
implementation 'androidx.recyclerview:recyclerview:1.3.1'
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
public class TableAdapter extends RecyclerView.Adapter<TableAdapter.ViewHolder> {
private List<List<String>> mData;
public TableAdapter(List<List<String>> data) {
mData = data;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_table, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
List<String> row = mData.get(position);
holder.bindData(row);
}
@Override
public int getItemCount() {
return mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private List<TextView> mTextViews;
public ViewHolder(@NonNull View itemView) {
super(itemView);
mTextViews = new ArrayList<>();
mTextViews.add((TextView) itemView.findViewById(R.id.text1));
mTextViews.add((TextView) itemView.findViewById(R.id.text2));
mTextViews.add((TextView) itemView.findViewById(R.id.text3));
// 添加更多列的TextView
}
public void bindData(List<String> row) {
for (int i = 0; i < row.size(); i++) {
mTextViews.get(i).setText(row.get(i));
}
}
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:id="@+id/text2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:id="@+id/text3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<!-- 添加更多列的TextView -->
</LinearLayout>
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private TableAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3)); // 設(shè)置3列的表格
mRecyclerView.setHasFixedSize(true);
List<List<String>> data = new ArrayList<>();
// 添加表格數(shù)據(jù)
data.add(Arrays.asList("1", "2", "3"));
data.add(Arrays.asList("4", "5", "6"));
data.add(Arrays.asList("7", "8", "9"));
mAdapter = new TableAdapter(data);
mRecyclerView.setAdapter(mAdapter);
}
}
通過以上步驟,就可以實(shí)現(xiàn)一個(gè)簡單的復(fù)雜表格控件。你可以根據(jù)需要自定義適配器和布局文件,來實(shí)現(xiàn)更加復(fù)雜的表格控件。