У меня возникла проблема с отображением ImageViews с правильным размером. Почти все сообщения, которые я прочитал, включают ImageViews, которые создаются в файле макета. Однако в моем случае я создаю ImageViews программно.Размер ImageView не отображается правильно
Я пытаюсь отобразить все изображения из определенной папки, расположенной в хранилище. Полученные растровые изображения будут помещены в ImageViews, которые содержатся в GridView.
Вот мой код:
//pass an array containing all images paths to adapter
imageGrid.setAdapter(new GridViewAdapter(getActivity(), FilePathStrings));
часть GridVewAdapter кода:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if(convertView == null){
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setPadding(5, 5, 5, 5);
imageView.setAdjustViewBounds(true);
}else{
imageView = (ImageView) convertView;
}
imageView.setTag(filepath[position]);
new LoadImages(imageView).execute();
return imageView;
}
AsyncTask для получения растровых изображений:
private class LoadImages extends AsyncTask<Object, Void, Bitmap> {
private ImageView imgView;
private String path;
private LoadImages(ImageView imgView) {
this.imgView = imgView;
this.path = imgView.getTag().toString();
}
@Override
protected Bitmap doInBackground(Object... params) {
Bitmap bitmap = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = 6;
bitmap = BitmapFactory.decodeFile(path, bmOptions);
try {
int dimension = getSquareCropDimensionForBitmap(bitmap);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);
}catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
if (!imgView.getTag().toString().equals(path)) {
return;
}
if(result != null && imgView != null){
imgView.setVisibility(View.VISIBLE);
imgView.setImageBitmap(result);
}else{
imgView.setVisibility(View.GONE);
}
}
}
метод, чтобы получить одинаковые размеры, так растровые изображения будут отображаться как площади:
private int getSquareCropDimensionForBitmap(Bitmap bitmap) {
int dimension;
//If the bitmap is wider than it is height then use the height as the square crop dimension
if (bitmap.getWidth() >= bitmap.getHeight()) {
dimension = bitmap.getHeight();
}
//If the bitmap is taller than it is width use the width as the square crop dimension
else {
dimension = bitmap.getWidth();
}
return dimension;
}
GridView в файле макет:
<GridView
android:id="@+id/imageGridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="30dp"
android:numColumns="5"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:layout_marginTop="30dp">
</GridView>
Результат, который я получил:
обведенной тонкая "линия" на самом деле являются ImageViews отображаются.
Любая помощь очень ценится. Заранее спасибо!
Вы пытались установить 'layout_height' в' "match_parent" '? – Kumiho
Я не могу этого сделать, поскольку над GridView есть другие виды, но я нашел решение. Спасибо за помощь! – Angeline