在layout xml文件中定義一個TabLayout,然後在代碼中動態添加數個TableRow,每個TableRow中再添加幾個TextView,Button。在實現過程中發現TableRow動態添加後不能顯示。
這個問題的原因是TableRow中的子控件 TextView 和 Button 在setLayoutParams時使用了LinearLayout.LayoutParams。
正確的用法應該是使用TextView/Button所在的父控件的佈局參數,即TableRow.LayoutParams。
同樣的,TableRow設置佈局參數時應該使用所在父控件的參數TableLayout.LayoutParams。
正確的示例代碼如下:
TableRow tablerow = new TableRow(getContext());
TableLayout.LayoutParams params = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
tablerow.setLayoutParams(params);
TextView week = new TextView(getContext());
TextView hour = new TextView(getContext());
Button deleteButton = new Button(getContext());
week.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT,0.4f));
hour.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT,0.4f));
deleteButton.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT,0.2f));
week.setText("weekday");
hour.setText("12:00"+ "--" + "12:30");
deleteButton.setText("—");
deleteButton.setBackgroundResource(R.drawable.circle_style);
tablerow.addView(week);
tablerow.addView(hour);
tablerow.addView(deleteButton);
courseTime.addView(tablerow);
不在同一個地方跌倒兩次。