EzDevInfo.com

imageview interview questions

Top imageview frequently asked interview questions

Android ImageView size not scaling with source image

I have a few ImageViews inside a LinearLayout. I need to scale down the ImageViews so that they maintain their aspect ratios whilst fitting inside the LinearLayout vertically. Horizontally, I just need them to be adjacent to each other.

I've made a simplified test bed for this which nests weighted Layouts so that I have a wide, but not very tall, LinearLayout for the ImageViews -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
    <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="5">
        <LinearLayout android:id="@+id/linearLayout3" android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1">
            <ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/test_image" android:scaleType="fitStart"></ImageView>
            <ImageView android:id="@+id/imageView2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/test_image" android:scaleType="fitStart"></ImageView>
        </LinearLayout>
        <LinearLayout android:id="@+id/linearLayout4" android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"></LinearLayout>
    </LinearLayout>
    <LinearLayout android:id="@+id/linearLayout2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"></LinearLayout>
</LinearLayout>

(In the Eclipse layout editor the images are clipped vertically and not scaled at all - but that's just one of those idiosyncrasies that we learn to love)

When run on hardware the images are scaled to the correct height whilst preserving their aspect ratio. My problem is that they are not next to each other. The height of each ImageView correctly matches the height of the LinearLayout. The width of each ImageView is the width of the unscaled image - the actual scaled down images appearing at the left side of their ImageViews. Because of this, I'm getting a large gap between the images.

Ideally I would like to manage this through XML though, if this is not possible, I understand that using a custom view may be the best solution.

I tried creating an IconView (extends ImageView) class which overrides onMeasure so that I could create image views of the necessary size by scaling the width depending on the height. But the parentWidth and parentHeight being passed into the function were the dimensions of the screen and not of the LinearLayout container.

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
  int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
  // Calculations followed by calls to setMeasuredDimension, setLayoutParams
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

So my questions are -

1) Can I amend the XML in some way to make it do what I need?

2) How do I make my custom class get the height of the LinearLayout so that I can calculate the necessary width for the custom images?

Thanks if you've managed to read this far. Even more thanks if you can point me in the direction of a solution!


Source: (StackOverflow)

How can I get zoom functionality for images?

Is there a common way to show a big image and enable the user to zoom in and out and pan the image?

Until now I found two ways:

  1. overwriting ImageView, that seems a little bit too much for such a common problem.
  2. using a webview but with less control over the overall layout etc.

Source: (StackOverflow)

Advertisements

Get Bitmap attached to ImageView

Given

ImageView image = R.findViewById(R.id.imageView);
image.setImageBitmap(someBitmap);

Is it possible to retrieve the bitmap?


Source: (StackOverflow)

Show Image View from file path in android?

I need to show image by using File name only not from the Resource id.

     ImageView imgView=new ImageView(this);
     imgView.setBackgroundResource(R.drawable.img1);

I have the image img1 in the drawable folder. I wish to show that image from the file how to do this.


Source: (StackOverflow)

How do you setLayoutParams() for an ImageView?

I want to set the LayoutParams for an ImageView but cant seem to find out the proper way to do it.

I can only find documentation in the API for the various ViewGroups, but not an ImageView. Yet the ImageView seems to have this functionality.

This code doesn't work...

myImageView.setLayoutParams(new ImageView.LayoutParams(30,30));

How do I do it?


Source: (StackOverflow)

Android: java.lang.ClassCastException: android.widget.imageView cannot be cast to android.widget.textView

I can't fix this problem on my listview template: i have the error as in the title of my post, but i won't cast imageview to textview. Here's my code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="200dip"
android:layout_weight="1"
android:paddingBottom="10dip" >

<TextView
    android:id="@+id/mq"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:text="Metri quadri"
    android:textColor="#33b5e5"
    android:textSize="14sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/citta"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/mq"
    android:layout_alignBottom="@+id/mq"
    android:layout_centerHorizontal="true"
    android:text="Citta"
    android:textColor="#33b5e5"
    android:textSize="14sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/prezzo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:text="Prezzo"
    android:textColor="#e1e1e1"
    android:textSize="14sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/nome"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:padding="5dip"
    android:scrollHorizontally="true"
    android:singleLine="true"
    android:text="@string/testolungo"
    android:textColor="#e1e1e1"
    android:textSize="20sp"
    android:textStyle="bold" />

<ImageView
    android:id="@+id/foto"
    android:layout_width="80dip"
    android:layout_height="60dip"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:contentDescription="Release"
    android:padding="5dip"
    android:scaleType="centerCrop"
    android:src="@drawable/stub" />

<TextView
    android:id="@+id/descsplash"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="Small Text"
    android:textSize="16sp"
    android:textStyle="italic" />

</RelativeLayout>

The error for the java code is on line 58 of my file, where i assign the TextView id to TextView mq:

    View vi=convertView;
    if(convertView==null)
    vi = inflater.inflate(R.layout.listlay, null);
    TextView nome=(TextView)vi.findViewById(R.id.nome);
    TextView mq=(TextView)vi.findViewById(R.id.mq); // here's the error (???)
    TextView citta=(TextView)vi.findViewById(R.id.citta);
    TextView prezzo=(TextView)vi.findViewById(R.id.prezzo);
    ImageView image=(ImageView)vi.findViewById(R.id.foto);
    TextView descrizione = (TextView)vi.findViewById(R.id.descsplash);
    nome.setText(data.get(position).getNome());
    mq.setText(data.get(position).getMetriQuadri());
    citta.setText(data.get(position).getCitta());
    prezzo.setText(data.get(position).getPrezzo());
    descrizione.setText(data.get(position).getDescrizione());
    imageLoader.DisplayImage(data.get(position).getForoUrl(), image);

And here is the logcat:

06-25 16:08:32.497: D/Debug(14642): Prendo Textview MQ
06-25 16:08:32.497: D/AndroidRuntime(14642): Shutting down VM
06-25 16:08:32.497: W/dalvikvm(14642): threadid=1: thread exiting with uncaught exception (group=0x40a561f8)
06-25 16:08:32.497: E/AndroidRuntime(14642): FATAL EXCEPTION: main
06-25 16:08:32.497: E/AndroidRuntime(14642): java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.TextView
06-25 16:08:32.497: E/AndroidRuntime(14642): at com.prova.listview.LazyAdapter.getView(LazyAdapter.java:58)

Does anyone know how i can fix this problem?


Source: (StackOverflow)

Android ImageView adjusting parent's height and fitting width

Update : I solved this issue by using the method described in this answer

I'm a bit stuck with this issue, which I think should be pretty simple.

So my app downloads an image, and renders the bitmap in an ImageView, a child element of a RelativeLayout. I would like the ImageView to fit the parent width, and to adapt it's size to keep the aspect ratio.

Here is my XML :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout android:id="@+id/banner" android:layout_width="fill_parent" android:layout_height="wrap_content"></RelativeLayout>
<TextView  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="@string/hello"
/>
</LinearLayout>

And the code :

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    RelativeLayout banner = (RelativeLayout) findViewById(R.id.banner);
    ImageView imgV = new ImageView(this);

    imgV.setScaleType(ImageView.ScaleType.CENTER_CROP);
    // I tried all the scale types : CENTER_INSIDE : same effect, FIT_CENTER : same effect... 

    imgV.setBackgroundColor(0x00FFFF00);

    imgV.setAdjustViewBounds(Color.BLUE);


    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

    banner.addView(imgV,params);

    // Some code downloading the image stream

    bitmap = BitmapFactory.decodeStream(stream);


    imgV.setImageBitmap(bitmap);

    }

Desired :

Desired result

Result :

Current result


Source: (StackOverflow)

Android fade in and fade out with ImageView

I'm having some troubles with a slideshow I'm building.

I've created 2 animations in xml for fade in and fade out:

fadein.xml

    <?xml version="1.0" encoding="UTF-8"?>
       <set xmlns:android="http://schemas.android.com/apk/res/android">
         <alpha android:fromAlpha="0.0" android:toAlpha="1.0" 
          android:interpolator="@android:anim/accelerate_interpolator" 
          android:duration="2000"/>
     </set>

fadeout.xml

    <?xml version="1.0" encoding="UTF-8"?>
       <set xmlns:android="http://schemas.android.com/apk/res/android">
         <alpha android:fromAlpha="1.0" android:toAlpha="0.0" 
          android:interpolator="@android:anim/accelerate_interpolator" 
          android:duration="2000"/>
     </set>

What Im'trying to do, is to change images from an ImageView using the fade effect, so the currently displayed image will fade out, and another one will fade in. Considering that I have an image already set, I can fadeout this Image without problem, with this:

    Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.your_fade_in_anim);
    imageView.startAnimation(fadeoutAnim);

But then, I set the next image to be displayed:

    imageView.setImageBitmap(secondImage);

It just shows up in the imageView, and when i set the animation it hides the image, the fade it in... Is there any way to fix that, I mean, when I do imageView.setImageBitmap(secondImage); command, the image do not shows up immediately, and only when the fade in animation is executed?


Source: (StackOverflow)

Full screen background image in an activity

I see many applications that use a full-screen image as background. This is an example:

Full screen background image

I want to use this in a project, the best way I've found so far to do this is to use an image with a large size, put it in a ImageView and use android: adjustViewBounds="true" to adjust the margins

The problem is that if a screen with a very high resolution, the image falls short.

Another option I thought of is to use the image in a FrameLayout, with match_parent in width and height as background... this stretches the image, but I think the result is not very good.

I can ask how would you do it?

Thanks in advance Regrads


Source: (StackOverflow)

Android imageview not respecting maxWidth?

So, I have an imageview that should display an arbitrary image, a profile picture downloaded from the internet. I want this the ImageView to scale its image to fit inside the height of the parent container, and a set max width of 60dip. However, if the image is tall ratio-wise, and doesn't need the full 60dip of width, the ImageView's width should decrease so the view's background fits snugly around the image.

I tried this,

<ImageView android:id="@+id/menu_profile_picture"
    android:layout_width="wrap_content"
    android:maxWidth="60dip"
    android:layout_height="fill_parent"
    android:layout_marginLeft="2dip"
    android:padding="4dip"
    android:scaleType="centerInside"
    android:background="@drawable/menubar_button"
    android:layout_centerVertical="true"/>

but that made the ImageView super large for some reason, maybe it used the intrinsic width of the image and wrap_content to set it - anyway, it didn't respect my maxWidth attribute.. Does that only work inside some types of containers? It's in a LinearLayout...

Any suggestions?


Source: (StackOverflow)

How to convert a Base64 string into a BitMap image to show it in a ImageView?

I have a Base64 String that represents a BitMap image.

I need to transform that String into a BitMap image again to use it on a ImageView in my Android app

How to do it?

This is the code that I use to transform the image into the base64 String:

//proceso de transformar la imagen BitMap en un String:
//android:src="c:\logo.png"
Resources r = this.getResources();
Bitmap bm = BitmapFactory.decodeResource(r, R.drawable.logo);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray();
//String encodedImage = Base64.encode(b, Base64.DEFAULT);
encodedImage = Base64.encodeBytes(b);

Source: (StackOverflow)

what's the difference between ImageView.ScaleType.CENTER_INSIDE and FIT_CENTER?

I can't tell the difference between ImageView.ScaleType.CENTER_INSIDE and ImageView.ScaleType. FIT_CENTER.

ImageView.ScaleType.CENTER_INSIDE

Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

ImageView.ScaleType. FIT_CENTER

Compute a scale that will maintain the original src aspect ratio, but will also ensure that src fits entirely inside dst. At least one axis (X or Y) will fit exactly. The result is centered inside dst.

Can someone illuminate the difference between the two?


Source: (StackOverflow)

Custom ImageView with drop shadow

Okay, I've been reading and searching around, and am now banging my head against the wall trying to figure this out. Here's what I have so far:

package com.pockdroid.sandbox;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.widget.ImageView;

public class ShadowImageView extends ImageView {

private Rect mRect;
private Paint mPaint;

public ShadowImageView(Context context)
{
    super(context);
    mRect = new Rect();
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setShadowLayer(2f, 1f, 1f, Color.BLACK);
}

@Override
protected void onDraw(Canvas canvas) 
{
    Rect r = mRect;
    Paint paint = mPaint;

    canvas.drawRect(r, paint);
    super.onDraw(canvas);
}

@Override
protected void onMeasure(int w, int h)
{
    super.onMeasure(w,h);
    int mH, mW;
    mW = getSuggestedMinimumWidth() < getMeasuredWidth()? getMeasuredWidth() : getSuggestedMinimumWidth();
    mH = getSuggestedMinimumHeight() < getMeasuredHeight()? getMeasuredHeight() : getSuggestedMinimumHeight();
    setMeasuredDimension(mW + 5, mH + 5);
}

}

The "+5" in the measurements are there as temporary; From what I understand I'll need to do some math to determine the size that the drop shadow adds to the canvas, right?

But when I use this:

public View getView(int position, View convertView, ViewGroup parent) {
    ShadowImageView sImageView;
    if (convertView == null) {
        sImageView = new ShadowImageView(mContext);
        GridView.LayoutParams lp = new GridView.LayoutParams(85, 85);
        sImageView.setLayoutParams(lp);

        sImageView.setScaleType(ImageView.ScaleType.CENTER);
        sImageView.setPadding(5,5,5,5);
    } else {
        sImageView = (ShadowImageView) convertView;
    }

    sImageView.setImageBitmap(bitmapList.get(position));
    return sImageView;
}

in my ImageView, I still get just a normal ImageView when I run the program.

Any thoughts? Thanks.

EDIT: So I spoke with RomainGuy some in the IRC channel, and I have it working now for plain rectangular images with the below code. It still won't draw the shadow directly to my bitmap's transparency though, so I'm still working on that.

@Override
protected void onDraw(Canvas canvas) 
{
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.omen);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShadowLayer(5.5f, 6.0f, 6.0f, Color.BLACK);
    canvas.drawColor(Color.GRAY);
    canvas.drawRect(50, 50, 50 + bmp.getWidth(), 50 + bmp.getHeight(), paint);
    canvas.drawBitmap(bmp, 50, 50, null);       
}

Source: (StackOverflow)

Unwanted padding around an ImageView

i need to include a header graphic in all of my activities/views. the file with the header is called header.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content"
  android:background="#0000FF" 
  android:padding="0dip">

  <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/header"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="0dip"
    android:layout_marginTop="0dip"
    android:layout_marginBottom="0dip"
    android:padding="0dip"
    android:paddingTop="0dip"
    android:paddingBottom="0dip"
    android:layout_gravity="fill"
    android:background="#00FF00"
    />
</FrameLayout>

note the android:background="#00FF00" (green), it's just visualisation purposes.

i include them into my views like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical"
  style="@style/white_background">

  <include layout="@layout/header" />
  (...)

so, when i actually try it out, the result looks like the left image, instead of what it should look like (right):

note the green border

(1) this - the orange - part is the image/ImageView in question
(2) the unloved green border. note: normally, the green area would be transparent - it's only green because i set the background.

note the green border around the image at the top; it's part of the ImageView and i just can't figure out why it is there or how i can get rid of it. it set all paddings and margins to 0 (but the result is the same when i omit them) . the image is a 480x64px jpeg* and i put it in res/drawable (not in one of the drawable-Xdpi though).

(* jpeg, because it seems i stumbled upon the old png gamma problem - at first i worked around the problem by making the green border the same orange as the picture, and the colors didn't match.)

i tried it on my htc desire/2.2/Build 2.33.163.1 and on the emulator. also i described the problem to someone in #android-dev; she could reproduce the problem but had no explanation either. build target is 1.6.

update @tehgoose: this code yields the exact same top+bottom padded result.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical"
  style="@style/white_background">

  <!-- <include layout="@layout/header" />  -->

  <ImageView
    android:src="@drawable/header"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#00FF00"
    android:layout_weight="0"
    />

  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dip"
    android:layout_weight="1">

    (... rest of the elements)

  </LinearLayout>
</LinearLayout>

Source: (StackOverflow)

Replace selector images programmatically

I have an ImageView that has a drawable image resource set to a selector. How do I programmatically access the selector and change the images of the highlighted and non-highlighted state?

Here is a code of selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/iconSelector">
  <!-- pressed -->
  <item android:state_pressed="true" android:drawable="@drawable/btn_icon_hl" />
  <!-- focused -->
  <item android:state_focused="true" android:drawable="@drawable/btn_icon_hl" />
  <!-- default -->
  <item android:drawable="@drawable/btn_icon" />
</selector>

I want to be able to replace btn_icon_hl and btn_icon with other images.


Source: (StackOverflow)