如何设置GridView控件编程机器人的高度 [英] how to set height of gridview programmatically android

查看:163
本文介绍了如何设置GridView控件编程机器人的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置的高度,是我的的GridView 编程方式在我的应用程序。

I want to set the height of my Gridview programmatically in my application.

有没有办法来实现呢?

Is there any way to implement that?

我只是想从code改变gridview的高度有两种particularcases。

I just want to change the gridview height in two particularcases from the code.

编辑:

<fragment
     android:id="@+id/mygridview"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_margin="10dip"
     class="com.myapp.android.MyGridViewClass" />

MyGridViewClass延伸片段,其中的GridView填充。

MyGridViewClass extends Fragment where Gridview is populated.

 <GridView
    android:id="@+id/mygridview_container"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dip"
    android:columnWidth="90dp"
    android:gravity="center_vertical|center_horizontal"
    android:horizontalSpacing="1dp"
    android:numColumns="3"
    android:scrollbars="vertical"
    android:stretchMode="spacingWidthUniform"
    android:verticalSpacing="5dp" />

在myGridViewClass onViewCreated ,我现在用的是code充气GridView控件,

In myGridViewClass onViewCreated, I am inflating the gridview using the code,

gridView = (GridView)getView().findViewById( R.id.mygridview_container);
gridAdapter = new MyCustomAdapter(context, list);
gridView.setAdapter(gridAdapter);   

每当创建视图我要检查在GridView的项目数,并设置相应的高度。

Whenever the view is created I have to check the number of items in the gridview and set the height accordingly.

当我尝试设置的LayoutParams()的gridview的,我得到这个例外。

When I tried setting the layoutParams() for gridview, I got this exception.

android.view.InflateException: Binary XML file line #89: Error inflating class fragment

在哪里线89对应于该行的片段     类=com.myapp.android.MyGridViewClass

Where line 89 corresponds to this line in the fragment class="com.myapp.android.MyGridViewClass"

推荐答案

只要你想保留当前使用此,的LayoutParams

Use this, as you want to retain the current layoutParams:

ViewGroup.LayoutParams layoutParams = yourGridview.getLayoutParams();
layoutParams.height = 50; //this is in pixels
yourGridview.setLayoutParams(layoutParams);

编辑:如果你想的不是像素输入高度 DP ,翻译 DP 量为像素

public static int convertDpToPixels(float dp, Context context){
    Resources resources = context.getResources();
    return (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp, 
            resources.getDisplayMetrics()
    );
}

这篇关于如何设置GridView控件编程机器人的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆