【发布时间】:2016-09-11 04:27:03
【问题描述】:
我正在开发一个 Android 应用程序,我必须创建一个由网格视图组成的布局,该网格视图具有两列具有固定宽度和一定数量的行。
这个 gridview 是由图像组成的,在我的网格的每个“正方形”中都有一个图像,我需要尺寸与屏幕的大小完全相同,我不想通过滚动来显示。
我可以固定长度,但不能固定高度。如何确保我的烤架符合我指定的尺寸?
这是我的布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="am.MainActivity"
tools:showIn="@layout/activity_main">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="2"
android:verticalSpacing="4dp"
android:horizontalSpacing="8dp"
android:stretchMode="columnWidth"/>
</RelativeLayout>
这是java代码:
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels / 2;
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setLayoutParams(new GridView.LayoutParams(width, width));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.bacheca, R.drawable.turni,
R.drawable.utility, R.drawable.contatti,
R.drawable.invia, R.drawable.info
};
}
输出非常适合宽度(屏幕尺寸中包含两个图像),但高度错误,因为当我宁愿将所有内容都显示在屏幕上时,它会激活滚动
【问题讨论】:
-
响应式是什么意思。如果你给定了换行内容的高度,那么它将由内容进行调整