我无法以编程方式获取 GridView 内容高度,因为我将其放置在 ScrollView 中,我只需要通过在PIXELS中获取其内容高度来动态拉伸 GridView 高度。这是我所做的:
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
System.out.println("...111Height..."+gridView.getMeasuredWidth());
}
但我想获取里面的值,OnCreate
以便我可以将它layoutParams.height
输入:
GridView gridView = (GridView) findViewById(R.id.gridview_module);
ViewGroup.LayoutParams layoutParams = gridView.getLayoutParams();
layoutParams.height = convertDpToPixels(iDontKnowWhatToPutHere, this);
gridView.setLayoutParams(layoutParams);
以及从像素转换为dp的方法:
public static int convertDpToPixels(float dp, Context context) {
Resources resources = context.getResources();
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
resources.getDisplayMetrics());
}
编辑:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".SecondActivity" >
<ScrollView
android:id="@+id/scrollview"
android:layout_width="match_parent"
android:layout_height="0"
android:layout_weight="1"
android:fillViewport="true"
android:scrollbars="none" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<com.example.ExpandableHeightGridView
android:id="@+id/gridview_module"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="@id/tv"
android:layout_weight="1"
android:gravity="center"
android:horizontalSpacing="20dp"
android:numColumns="3"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
<Button
android:id="@+id/dial_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/gridview_module"
android:onClick="dialPhone"
android:text="Dial Phone" />
</LinearLayout>
</ScrollView>