【问题标题】:Android - set button width programmatically inside a tablerowAndroid - 在表格中以编程方式设置按钮宽度
【发布时间】:2013-07-26 13:13:52
【问题描述】:

我有一个在表格视图中生成按钮的应用程序,如下所示:

TableLayout table = (TableLayout) findViewById( R.id.tableLayout1 );

    for(int i = 0 ; i < Gatorade.getVariant().length ; i++){
           int buttonsInRow = 0;
           int numRows = table.getChildCount();

           TableRow row = null;

           if( numRows > 0 ){
                row = (TableRow) table.getChildAt( numRows - 1 );
                buttonsInRow = row.getChildCount();         
           }

           if( numRows == 0 || buttonsInRow == 3 ){
                row = new TableRow( this );
                table.addView( row );
                buttonsInRow = 0;
           }
           if( buttonsInRow < 3 ){
                Button b = new Button( this );
                b.setText(Gatorade.getVariant()[i]);
                //b.setWidth(pixels)
                //b.setWidth()

                row.addView( b, 100, 50 );

           }
}

有没有办法以编程方式将按钮宽度设置为wrap_content,将高度设置为match_parent

如果这是不可能的,有没有办法以编程方式均匀地隔开行中的按钮?

谢谢。

【问题讨论】:

    标签: android button tablelayout tablerow


    【解决方案1】:

    试试这个:

    LayoutParams lp = new TableRow.LayoutParams(android.widget.TableRow.LayoutParams.WRAP_CONTENT,android.widget.TableRow.LayoutParams.MATCH_PARENT);
    btn.setLayoutParams(lp);
    

    尝试在按钮中使用权重。给表格行 weightsum=10。并根据您的要求将其划分为按钮。像 btn1.weight=3; btn2.weight=5;btn3.weight=2;这就像在 HTML 中使用 % 一样。如果你设置 weightsum = 10 这意味着它将使用其父视图的 100%。并且对按钮使用 weight=3 意味着它将使用总行大小的 3/10。它仅用于宽度,因此您需要为要分配权重的每个视图设置宽度 =0。

    这样的体重使用:

    LayoutParams lp = new TableRow.LayoutParams(0,android.widget.TableRow.LayoutParams.MATCH_PARENT,3f);
    

    其中 3f 是重量。但首先在表格中设置权重总和为 10。

    希望对你有帮助!!!

    【讨论】:

    • 感谢它帮助很大。但是,按钮内容似乎太长了,第三行几乎看不到了。关于如何在表格行中均匀分布按钮的任何想法?
    猜你喜欢
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 2016-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    相关资源
    最近更新 更多