我需要左边和右边的一个。所有配置都应该通过代码完成。截图:
代码:
super.onCreate(savedInstanceState);
setContentView(R.layout.overview);
loadData();
TableLayout tl = (TableLayout)findViewById(R.id.tl);
TableRow tr = new TableRow(this);
TableRow tr2 = new TableRow(this);
tr.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
//tr2.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
//tr2.setLayoutParams(new ViewGroup.LayoutParams(L., LayoutParams.WRAP_CONTENT));
TextView tv = new TextView(this);
TextView tv2 = new TextView(this);
//tv.se
tv.setGravity(Gravity.LEFT);
tv2.setGravity(Gravity.RIGHT);
tv.setText("Test");
tv2.setText("Test");
//tv.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f));
//tv.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
tv2.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f));
//tv.setTextSize(50);
//tv2.setTextSize(50);
tr.addView(tv);
tr.addView(tv2);
//tl.addView(tr);
//setContentView(tl);
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
}
布局:
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/tl"
android:stretchColumns="*">
</TableLayout>
答案 0 :(得分:2)
视图使用LayoutParams告诉他们的父母他们想要如何布局。 Android中定义了大约13种不同类型的LayoutParams。例如。 LinearLayout.Layoutparams,ViewGroup.LayoutParams,ActionBar.LayoutParams等。
因此,如果将TextView添加到LinearLayout,则意味着LinearLayout是TextView的父级,因此在为textView定义布局参数时应该使用 LinearLayout.LayoutParams而不是ViewGroup.LayoutParams
在你的情况下你要向表格行添加两个文本视图,所以很明显你应该使用TableRow.LayoutParams
所以替换这一行
tv2.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f));
与
tv2.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f));
同样写电视 这是我在这个网站上的第一篇文章。希望它会有所帮助:)
答案 1 :(得分:0)
我认为你必须使用:
android:stretchColumns="0,1"
可以找到很好的例子here
这样做:
从tv2 layoutparams中删除1f。
tl.addView(tr,new TableLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
这可以根据给定的链接解决您的问题。