2013-07-02 3 views
1

У меня очень странная проблема, которую я, похоже, не могу исправить.ImageView внутри ScrollView не будет изменять размер, чтобы заполнить экран (сохраняющий аспект)

Я не могу изменить размер растрового изображения для ImageView, который находится внутри ScrollView. Я тестировал один и тот же макет (но без прокрутки), и изображение менялось так, как должно быть.

Я нашел других, имеющих такую ​​проблему, и для большинства использования android:fillViewport="true" было бы достаточно, но для меня это не работает.

Вот мой макет:

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"  
     android:fillViewport="true" 
     android:background="@drawable/bg_app" > 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" > 

     <RelativeLayout 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_margin="5dp" 
      android:background="@drawable/custom_white_background" 
      android:padding="5dp"> 

      <ImageView 
       android:id="@+id/full_image_view" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:adjustViewBounds="true" 
       android:scaleType="fitCenter" 
       android:src="@drawable/bg_app" 
       android:contentDescription="@string/otl_img_description" 
       android:layout_margin="5dp" 
       android:padding="5dp" />    

      <View 
       android:id="@+id/divider2" 
       android:layout_width="match_parent" 
       android:layout_height="3dp" 
       android:layout_below="@+id/full_image_view" 
       android:layout_centerHorizontal="true" 
       android:layout_marginLeft="5dp" 
       android:paddingRight="5dp" 
       android:layout_marginRight="5dp" 
       android:paddingLeft="5dp" 
       android:alpha="0.3" 
       android:background="@color/black_50" 
       android:fadingEdge="horizontal" /> 

      <TextView 
       android:id="@+id/onthelist_animal_name" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_alignParentBottom="true" 
       android:layout_alignParentLeft="true" 
       android:layout_below="@+id/full_image_view" 
       android:layout_margin="5dp" 
       android:layout_toLeftOf="@+id/onthelist_animal_date" 
       android:gravity="left|center" 
       android:padding="5dp" 
       android:text="@string/otl_animal_name" 
       android:textColor="@color/blue" 
       android:textStyle="bold" 
       android:textSize="18sp" /> 

      <TextView 
       android:id="@+id/onthelist_animal_date" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_below="@+id/full_image_view" 
       android:layout_centerHorizontal="true" 
       android:layout_margin="5dp" 
       android:gravity="center" 
       android:padding="5dp" 
       android:text="@string/otl_animal_date" 
       android:textColor="#a00000" 
       android:textStyle="bold" 
       android:textSize="18sp" /> 

      <ImageButton 
       android:id="@+id/onthelist_share" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_alignBottom="@+id/onthelist_animal_date" 
       android:layout_alignParentBottom="true" 
       android:layout_alignParentRight="true" 
       android:layout_alignTop="@+id/onthelist_animal_date" 
       android:layout_toRightOf="@+id/onthelist_animal_date" 
       android:adjustViewBounds="true" 
       android:paddingRight="5dp" 
       android:contentDescription="@string/otl_animal_share" 
       android:scaleType="fitEnd" 
       android:src="@android:drawable/ic_menu_share" 
       android:background="@android:color/transparent" />   

     </RelativeLayout> 

     <Button 
      android:id="@+id/onthelist_save" 
      style="@style/ButtonText" 
      android:layout_height="wrap_content" 
      android:background="@layout/custom_red_button" 
      android:text="@string/otl_save" 
      android:layout_margin="5dp" 
      android:padding="5dp" /> 

     <TextView 
      android:id="@+id/onthelist_animal_description" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_margin="5dp" 
      android:background="@drawable/custom_white_background" 
      android:padding="5dp" 
      android:textAppearance="?android:attr/textAppearanceSmall" 
      android:textColor="@color/black" 
      android:text="@string/otl_animal_description" 
      android:linksClickable="true" /> 

    </LinearLayout> 
</ScrollView> 

и я устанавливаю изображение для ImageView full_image_view как это:

 imageView = (ImageView) findViewById(R.id.full_image_view); 
    Log.i("OnTheList", "itemID[FI] = " + position); 
    try { 
     imageView.setImageBitmap(new ImageLoadTask().execute(
       JSONParserOnTheList.ANIMALS.get(position).photo).get());    
    } catch (InterruptedException e) { 
     imageView.setImageResource(R.drawable.default_photo); 
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     imageView.setImageResource(R.drawable.default_photo); 
     e.printStackTrace(); 
    } 

AsyncTask возвращает Bitmap.

спасибо.

РЕД (РЕШЕНИЕ -> FIX)

После многих вещей и применявшиеся методы, пытаясь решить проблему, я нашел решение. Идея заключалась в том, что макет работал нормально, проблема заключалась в том, что на некоторых устройствах из-за плотности пикселей изображение изменялось в меньшей версии.

Исправление, которое я применил, было непосредственно в asynctask, когда я декодировал растровое изображение.

Так расположение и все остальное осталось прежним и asyntask это:

private class ImageLoadTask extends AsyncTask<String, Void, Bitmap> { 
    private Bitmap bitmap; 
    @Override 
    protected void onPreExecute() { 
     loading.setTitle("Loading image ..."); 
     loading.show(); 
     super.onPreExecute(); 
    } 

    @Override 
    protected Bitmap doInBackground(String... params) { 
     try { 
      URL url; 
      url = new URL(params[0]); 
      HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoInput(true); 
      connection.connect(); 
      InputStream input = connection.getInputStream(); 
      BitmapFactory.Options options = new BitmapFactory.Options(); 

      // Bitmap scale depending on density 
      // For example: 
      // 1600*1200 image to be resized to 640*480 
      // (1600*2 equal to 640*5) 
      options.inDensity = 5; 
      options.inTargetDensity = 2; 
      options.inScaled = false; 
      // Decode the bitmap 
      bitmap = BitmapFactory.decodeStream(input, null, options); 
      input.close(); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return bitmap; 
    } 

    @Override 
    protected void onPostExecute(Bitmap result) { 
     loading.dismiss(); 
     loading.cancel(); 
     super.onPostExecute(result); 
    } 
} 

Обратите внимание на варианты BitmapFactory, что является важной частью, которая устраняет проблему.

Кроме того, чтобы не иметь очень большое изображение (так называемые полный размер) вы можете дать размеры в зависимости от размера экрана, как это:

ImageView imageView = (ImageView) findViewById(R.id.full_image_view); 
imageView.setMaxHeight(screenSize()[0]-150); 
imageView.setMaxWidth(screenSize()[1]-150); 


private int[] screenSize() { 
    DisplayMetrics metrics = new DisplayMetrics(); 
    getWindowManager().getDefaultDisplay().getMetrics(metrics); 

    int height = metrics.heightPixels; 
    int width = metrics.widthPixels; 

    return new int[] {height, width}; 

Надеется, что это помогает кто-нибудь, что борется с этим в будущее. }

+0

После некоторых тестов я обнаружил, что это может быть потому, что я помещаю растровое изображение внутри ImageView ... Когда я поместил одно и то же изображение в ImageView из макета drawable через XML, он будет изменен в порядке. Кто-нибудь знает, как я могу это исправить? Спасибо! –

+0

Еще одна вещь, которую я заметил, это то, что все работает хорошо на некоторых устройствах. Из того, что у меня есть для тестирования, результаты выглядят так: Он работает для Samsung Galaxy Tab 2.0 и HTC Desire Bravo. Он НЕ работает для: Samsung Galaxy S4. Что может быть причиной этого? –

ответ

0

Пожалуйста, укажите проблему слово за словом, для других изменений части все из:

android:layout_below="@+id/full_image_view" 
android:layout_alignBottom="@+id/onthelist_animal_date" 
android:layout_alignTop="@+id/onthelist_animal_date" 
android:layout_toRightOf="@+id/onthelist_animal_date" 

To:

android:layout_below="@id/full_image_view" 
android:layout_alignBottom="@id/onthelist_animal_date" 
android:layout_alignTop="@id/onthelist_animal_date" 
android:layout_toRightOf="@id/onthelist_animal_date" 

Е.Г. - Удалить «+», это используется только для «android:id» и маркирует имя макета.

+0

Проблема заключается в том, что изображение, которое отображается, не изменяется, как оно должно быть (оно меньше, гораздо меньше), то есть я хочу, чтобы оно изменялось в зависимости от размера экрана устройства (но также сохраняло его пропорции). Расположение элементов в макете не является проблемой, но размер ImageView! –

2

Пожалуйста, добавьте fadingEdge и fillViewport в Scrollview

<ScrollView 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"  
     android:fillViewport="true" 
     android:fadingEdge="none" 
     android:background="@drawable/bg_app" > 
0

Here реальное простое решение! использовать android:scaleType="fitXY" в вашем ImageView.

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