我正在尝试动态创建TableRow对象,并将它们添加到tableelayout。 TableRow对象有两个项,一个TextView和一个CheckBox。TextView项需要将其布局权重设置为1,以将CheckBox项推到最右边。
我找不到关于如何以编程方式设置TextView项的布局权重的文档。
我正在尝试动态创建TableRow对象,并将它们添加到tableelayout。 TableRow对象有两个项,一个TextView和一个CheckBox。TextView项需要将其布局权重设置为1,以将CheckBox项推到最右边。
我找不到关于如何以编程方式设置TextView项的布局权重的文档。
当前回答
TextView text = new TextView(v.getContext());
text.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1f));
(OR)
TextView tv = new TextView(v.getContext());
LayoutParams params = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
tv.setLayoutParams(params);
1f表示weight=1;根据您的需要,您可以给出2f或3f,视图将根据空间移动。为了在线性布局中使视图之间的指定距离使用weightsum For“LinearLayout”。
LinearLayout ll_Outer= (LinearLayout ) view.findViewById(R.id.linearview);
LinearLayout llInner = new LinearLayout(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FillParent, LinearLayout.LayoutParams.WrapContent);
llInner.Orientation = Orientation.Horizontal;
llInner.WeightSum = 2;
ll_Outer.AddView(llInner);
其他回答
TextView txtview = new TextView(v.getContext());
LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
txtview.setLayoutParams(params);
1f表示weight=1;你可以给2f或3f,视图将根据空间移动
经过4个小时的挣扎。 最后,这段代码为我工作了。
3列是一排的。
TextView serialno = new TextView(UsersActivity.this);
TextView userId = new TextView(UsersActivity.this);
TextView name = new TextView(UsersActivity.this);
serialno.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
userId.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
name.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
还有另一种方法。如果你只需要设置一个参数,例如'height':
TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);
答案是您必须使用TableRow。LayoutParams,不是LinearLayout。LayoutParams或任何其他LayoutParams。
TextView tv = new TextView(v.getContext());
LayoutParams params = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
tv.setLayoutParams(params);
不同的LayoutParams是不可互换的,如果你使用了错误的LayoutParams,那么似乎什么都不会发生。文本视图的父视图是一个表行,因此:
http://developer.android.com/reference/android/widget/TableRow.LayoutParams.html
这对我有用,我希望对你也有用
首先为父视图设置LayoutParams:
myTableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.FILL_PARENT));
然后为TextView(子)设置:
TableLayout.LayoutParams textViewParam = new TableLayout.LayoutParams
(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT,1f);
//-- set components margins
textViewParam.setMargins(5, 0, 5,0);
myTextView.setLayoutParams(textViewParam);