【问题标题】:Layoutparams set weight in codeLayoutparams 在代码中设置权重
【发布时间】:2013-12-05 21:18:10
【问题描述】:

您好,我在 XML 中创建了 TableLayout 现在在代码中,我通过 finViewById 引用 tablelayout。然后我动态创建包含四个子项的新 TableRow(row2)(当我单击 dodaj_wiersz 按钮时会发生)。 Textv1,Editt1, Textv2, Editt2

我的问题是,我怎样才能为行设置均匀的权重,就像在 XML 中使用“均匀分配权重”按钮之后一样。

我的代码:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setContentView(R.layout.nowe_sciany);

        final TableLayout tablayout=(TableLayout) findViewById(R.id.wyglad);

        //reakcja na dodaj wiersz
        final Button dodaj_wiersz=(Button) findViewById(R.id.addrow);
        dodaj_wiersz.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                TableRow row2 = new TableRow(getApplicationContext());

                textv1 = new TextView(getApplicationContext());
                textv2 = new TextView(getApplicationContext());
                editt1 = new EditText(getApplicationContext());
                editt2 = new EditText(getApplicationContext());
                textv1.setText("width: ");
                textv2.setText("height: ");

                row2.addView(textv1);
                row2.addView(editt1);
                row2.addView(textv2);
                row2.addView(editt2);

                tablayout.addView(row2, new TableLayout.LayoutParams());                            
            }           
        });         
    }
    @Override
    public void onClick(View v) {

}
}

【问题讨论】:

    标签: java android tablelayout


    【解决方案1】:

    如果您在 TableRow 中固定了 4 个视图(Textv1、Editt1、Textv2、Editt2),那么您可以像这样定义 TableLayout:

    TableRow.layoutParams trLayout = 
                        new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f);
    tablayout.addView(row2, trLayout);
    

    要创建一个线性布局,其中每个孩子在屏幕上使用相同数量的空间,请将每个视图的 android:layout_height 设置为“0dp”(对于垂直布局)或每个视图的 android:layout_width 设置为“ 0dp”(用于水平布局)。

    LinearLayout 是 TableRowLayout #doc 的父级

    【讨论】:

    • 在 XML 中,我只创建了 TableLayout,因此我无法将每个视图的“android:layout_height”设置为“0dp”。这是基本示例,因为我必须创建 2x 行。所以我不能在 xml 中创建 LinearLayout。
    • 不,我刚刚提到这一点,因为我在回答中使用了0。顺便说一句,你的问题解决了。
    【解决方案2】:

    您可以像这样在 layoutparams 上设置权重:

    TableRow.LayoutParams params = new TableRow.LayoutParams(
        LayoutParams.MATCH_PARENT,
        LayoutParams.MATCH_PARENT, 1.0f);
    

    参数是宽度、高度和重量。

    然后您可以将参数设置为视图:

    textv1.setLayoutParams(params);
    

    【讨论】:

    • 如果我尝试这个,这是一个错误构造函数 TableRow(int, int, float) 未定义
    • 我的错误,代码中的错字(应该是 TableRow.LayoutParams)。更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2019-04-07
    • 2012-04-03
    • 2021-08-14
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    相关资源
    最近更新 更多