我正在尝试为动态创建的表列设置分隔符。我的TableLayout的xml:
<TableLayout
android:id="@+id/tableEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@drawable/table_header_divider"/>
我动态添加列的部分:
TableRow headerrow = new TableRow(this.getActivity());
addTableHeader("Type", 175, headerrow);
addTableHeader("Exp", 175, headerrow);
headerrow.setBackground(ContextCompat.getDrawable(this.getActivity(), R.drawable.selector_table_header));
headerrow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
tableEdit.addView(headerrow);
private void addTableHeader(String title, int colWidth, TableRow headerrow) {
TextView textview = new TextView(this.getActivity());
textview.setText(title);
textview.setLayoutParams(new android.widget.TableRow.LayoutParams(colWidth, android.widget.TableRow.LayoutParams.WRAP_CONTENT));
headerrow.addView(textview);
}
但是,分隔图像完全没有显示。有任何想法吗?还是有什么办法以编程方式设置分频器?谢谢!
答案 0 :(得分:1)
尝试一下
private void addTableHeader(String title, int colWidth, TableRow headerrow) {
TextView textview = new TextView(this);
textview.setText(title);
textview.setLayoutParams(new android.widget.TableRow.LayoutParams(colWidth, android.widget.TableRow.LayoutParams.WRAP_CONTENT));
headerrow.addView(textview);
View v = new View(this);
v.setLayoutParams(new TableRow.LayoutParams(3, TableRow.LayoutParams.MATCH_PARENT));
v.setBackgroundColor(Color.RED);
headerrow.addView(v);
}
编辑,您可以添加布尔标志来检查是否需要添加分隔线的天气
public class MyActivity extends AppCompatActivity {
TableLayout tableEdit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
tableEdit = findViewById(R.id.tableEdit);
TableRow headerrow = new TableRow(this);
addTableHeader("Type", 175, headerrow, true);// send true if you want to add devider
addTableHeader("Exp", 175, headerrow, false);// send false if you don't want to add devider
headerrow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
tableEdit.addView(headerrow);
}
private void addTableHeader(String title, int colWidth, TableRow headerrow, boolean flag) {
TextView textview = new TextView(this);
textview.setText(title);
textview.setLayoutParams(new android.widget.TableRow.LayoutParams(colWidth, android.widget.TableRow.LayoutParams.WRAP_CONTENT));
headerrow.addView(textview);
if (flag) {
View v = new View(this);
v.setLayoutParams(new TableRow.LayoutParams(3, TableRow.LayoutParams.MATCH_PARENT));
v.setBackgroundColor(Color.RED);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
params.leftMargin = 100;
params.rightMargin = 200;
v.setLayoutParams(params);
headerrow.addView(v);
}
}
}