問題描述
GridView kéo dài ImageView không đồng nhất (GridView Stretching ImageView Non‑Uniformly)
I have a GridView that I am using to display a row of 4 images, each image is 200 x 200 pixels. Here is the layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<GridView
android:id="@+id/myGridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:numColumns="4" >
</GridView>
</RelativeLayout>
When I run my app here is what the images look like:
As you can see the images are getting scaled (narrowed) to fit the screen.
How do I make it so the images are stretched both vertically and horizontally to maintain the correct aspect ratio?
Note that I am using an adapter to draw the images:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
} else {
imageView = (ImageView) convertView;
}
imageView.setBackgroundResource(imageIds[position]);
return imageView;
}
參考解法
方法 1:
I got the same issue in last weak.Use my image view class and solve this issue.
public class iv_autoSizedImageView extends ImageView {
public iv_autoSizedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto‑generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
try {
getLayoutParams().height = getMeasuredWidth();
} catch (Exception e) {
// TODO: handle exception
}
}
}
layout.xml
<com.sample.test.iv_autoSizedImageView
android:id="@+id/IV_NEWS_IMAGE"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>