以编程方式设置TextView的布局权重

223
我正在尝试动态创建TableRow对象并将它们添加到TableLayout中。 这些TableRow对象包含两个项目,一个TextView和一个CheckBox。需要将TextView的布局权重设置为1,以将CheckBox推到最右边。
我找不到如何以编程方式设置TextView项目的布局权重的文档。
12个回答

1

还有另一种方法可以实现这个功能。如果你只需要设置一个参数,比如说'height':

TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);

-1

我在解决类似问题时遇到了一些困难:尝试在TableRow中放置两个按钮,每个按钮占据屏幕宽度的一半。但不知何故,左侧按钮总是约占宽度的70%,右侧按钮则为30%。调用table_layout.setStretchAllColumns(true)没有效果,将按钮宽度设置为屏幕的一半或设置其布局权重也无济于事。

最终我采用的解决方案是在TableRows中嵌套一个LinearLayout,这样可以考虑到按钮宽度的值。

    TableLayout layout = new TableLayout(this);
    TableRow top_row = new TableRow(this);
    left_button = styleButton();
    right_button = styleButton();
    LinearLayout toprow_layout = new LinearLayout (this);
    toprow_layout.setOrientation(LinearLayout.HORIZONTAL);
    toprow_layout.addView (left_button);
    toprow_layout.addView(right_button);
    toprow.addView(top_layout);
    layout.addView(top_row)

    private Button styleButton() {
            Button btn = new Button (this);
            android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();      
            btn.setWidth((int)(display.getWidth()/2));    // set width to half
            btn.setHeight(((int)display.getHeight()/6));  // set height to whatevs
            btn.setText("foo");
            return btn;
        }

1
只是让你知道,未来的解决方案是将TableRow、Button1和Button2都设置为layout_width=fill_parent,然后在此之后,将button1和button2的layout_weight=1。所有具有fill_parent和layout_weight=1的元素在膨胀时将被赋予相等的大小。 - edthethird

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接