将视图高度设置为0dp,以编程方式将权重设置为1

时间:2018-01-22 10:57:20

标签: android android-layout android-linearlayout android-view android-layout-weight

通过xml创建GridView时我使用下面的代码,但是如何在运行时以编程方式实现?

    android:layout_height="0dp"
    android:layout_weight="1"

感谢。

2 个答案:

答案 0 :(得分:2)

使用此

GridView YOUR_GRID_VIEW =(GridView )findViewById(R.id.GridView )
    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                       /*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
               /*height*/ 0,
               /*weight*/ 1.0f
                );
                YOUR_GRID_VIEW.setLayoutParams(param);

LayoutParams.MATCH_PARENT表示宽度,0表示高度,1.0f表示重量

答案 1 :(得分:1)

如果您在xml中有layout_weight,则表示GridView的父布局为LinearLayout

引用已附加到视图层次结构的GridView,您只需获取该视图的LayoutParams,将其转换为LinearLayout.LayoutParams并执行必要的更改:


    GridView gridView = ...;
    LinearLayout.LayoutParams params = gridView.getLayoutParams();
    params.weight = 1;
    params.height = 0;
    gridView.setLayoutParams(params);

否则,如果您从头开始构建GridView,则应自行创建LinearLayout.LayoutParams


    LinearLayout linearLayout = ...;
    GridView gridView = new GridView(context);
    LinearLayout.LayoutParams params = 
              new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
                          /* height */ 0,
                          /* weight */ 1);
    linearLayout.addView(gridView, params);