2015-05-14 3 views
1

У меня возникла проблема с отображением 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> 

Результат, который я получил:

imgview_result

обведенной тонкая "линия" на самом деле являются ImageViews отображаются.

Любая помощь очень ценится. Заранее спасибо!

+0

Вы пытались установить 'layout_height' в' "match_parent" '? – Kumiho

+0

Я не могу этого сделать, поскольку над GridView есть другие виды, но я нашел решение. Спасибо за помощь! – Angeline

ответ

0

У меня есть другие взгляды выше GridView, так что я не могу установить его высоту fill_parent/match_parent в файле .xml, как это будет влиять на мнения выше.

Решение моей проблемы состоит в том, чтобы установить высоту и ширину GridView программно.

Заменить:

imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); 

С этим:

imageView.setLayoutParams(new GridView.LayoutParams(int height, int width)); 

Объяснение:

Grid View doc

Любой, кто имеет лучший ответ, пожалуйста, напишите его :)

0
<GridView 
android:id="@+id/imageGridView" 
android:layout_width="match_parent" 
android:layout_height="fill_parent" 
android:numColumns="auto_fit" 
android:verticalSpacing="5dp" 
android:horizontalSpacing="5dp" 
android:stretchMode="columnWidth" 
android:gravity="center" 
android:layout_marginTop="30dp"> 
+0

Есть другие виды над GridView, поэтому я не смогу установить высоту fill_parent. Я прибегал к настройке высоты и ширины GridView программно, и он работает. Спасибо за помощь :) – Angeline

Смежные вопросы