我从头开始解决了这个问题。
创建了一个黑色 Fragment 并将 TableLayout 添加到我以编程方式添加 TableRows 和 TextViews 的 XML。
<TableLayout
android:id="@+id/dataTableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="64dp">
</TableLayout>
在 DataTable java 文件中,我使用 newInstance 方法创建了一个带有标题、标题和数据作为参数的新片段:
public static DataTable newInstance(ArrayList<String> headers, ArrayList<ArrayList<String>> data, String title) {
DataTable fragment = new DataTable();
fragment.setTableTitle(title);
fragment.setHeaders(headers);
fragment.setData(data);
return fragment;
}
在onCreateView 方法中,我创建了所有的TableRows 和TextView。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_data_table, container, false);
TableLayout tableContainer = view.findViewById(R.id.dataTableLayout);
LinearLayout ll = new LinearLayout(this.getContext());
ll.setBackground(ContextCompat.getDrawable(this.getContext(),R.drawable.bottom_border));
tableContainer.addView(ll);
for (int headerCount = 0; headerCount < columns; headerCount++){
TextView tvn = new TextView(this.getContext());
tvn.setText(headers.get(headerCount));
tvn.setLayoutParams(new TableLayout.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
tvn.setPadding(24,10,10,10);
tvn.setMinWidth(200);
tvn.setTextColor(ContextCompat.getColor(this.getContext(),R.color.table_header_font_color));
tvn.setTextSize(getResources().getDimension(R.dimen.data_table_text_size_header));
ll.addView(tvn);
}
for(int rowCount = 0 ; rowCount < rows-1 ; rowCount++){
LinearLayout lld = new LinearLayout(this.getContext());
tableContainer.addView(lld);
for(int columnCount = 0; columnCount < columns; columnCount++){
TextView tvd = new TextView(this.getContext());
tvd.setText(data.get(rowCount).get(columnCount));
tvd.setLayoutParams(new TableLayout.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
tvd.setPadding(24,10,10,10);
tvd.setTextColor(ContextCompat.getColor(this.getContext(),R.color.table_data_font_color));
lld.addView(tvd);
}
if(rowCount+2 < columns){
lld.setBackground(ContextCompat.getDrawable(this.getContext(),R.drawable.bottom_border));
}
}
if(tableTitle != null){
TextView tableTitleVw = (TextView)view.findViewById(R.id.table_header);
tableTitleVw.setText(tableTitle);
}
return view;
}
我想对标题和数据做不同的事情,这就是我添加两个 for 循环的原因,如果你只想添加数据,一个循环就足够了。
如果需要对表格进行排序,可以使用我找到的一个库:https://github.com/ISchwarz23/SortableTableView
我不想依赖另一个库,也不需要所有这些额外的功能,这就是我自己实现它的原因。