我想以编程方式将TabeLayout添加到LinearLayout。 这是我的activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/content">
</LinearLayout>
这就是我在MainActivity中添加表的方法
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.content);
String[] content = new String[] {"Hello", "World", "Test"};
float d = getResources().getDisplayMetrics().density;
int dp = (int)(3*d);
TableLayout.LayoutParams tableParams =
new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT);
TableRow.LayoutParams rowParams =
new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
TableLayout table = new TableLayout(this);
table.setLayoutParams(tableParams);
for(int i = 0; i < content.length; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(rowParams);
int length = content[i].length();
TextView textView = new TextView(this);
textView.setLayoutParams(rowParams);
textView.setText(content[i]);
textView.setPadding(dp, 0, dp, 0);
row.setBackgroundColor(Color.BLUE);
row.addView(textView);
table.addView(row);
}
table.setBackgroundColor(Color.GRAY);
linearLayout.addView(table);
}
}
如您所见,tableParams设置为wrap_content。但是,当我设置我看到的表的背景颜色时,表的宽度与显示一样长。为什么会这样,我怎么能改变它呢?
答案 0 :(得分:0)
TableLayout处理宽度有点不同。 您需要让TableLayout知道它可以缩小列 尝试:
try {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String command = " ";
while (command != null) {
System.out.print(">>> ");
command = r.readLine();
processCommand(command);
}
} catch (IOException e) {
System.out.println("Something went wrong.");
}
查看TableLayout的参考文档。特别要注意的是:
表的总宽度由其父容器定义。
另外,作为提示,您可以替换:
table.setShrinkAllColumns(true);
使用:
table.setLayoutParams(tableParams);
linearLayout.addView(table);