Frage

I am trying to get the height & width of ImageView bot it's returning 0

public class FullScreenImage extends FragmentActivity {
    ImageView full_view;
    int width;
    int height;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);

        setContentView(R.layout.full_screen);

        full_view   = (ImageView)findViewById(R.id.full_view);

        Bundle bundle=getIntent().getExtras();
        byte[] image=   bundle.getByteArray("image");

        width       =     full_view.getWidth();
        height      =     full_view.getHeight();

        Bitmap theImage = BitmapFactory.decodeByteArray(image, 0, image.length);
        Bitmap resized = Bitmap.createScaledBitmap(theImage,width , height, true);

        full_view.setImageBitmap(resized);
    }


}

Please help me, how to find it from ImageView?

War es hilfreich?

Lösung

A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view’s constructor is called, Android doesn't know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the onSizeChanged() method to be notified of the values when they are known, or you can use the getWidth() and getHeight() methods later, such as in the onDraw() method.

Andere Tipps

see this

int finalHeight, finalWidth;
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
final TextView tv = (TextView)findViewById(R.id.size_label);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
    finalHeight = iv.getMeasuredHeight();
    finalWidth = iv.getMeasuredWidth();
    tv.setText("Height: " + finalHeight + " Width: " + finalWidth);
    return true;
  }
});

IF you first time get height and width that time there are no image available so result is 0.

Please use this code:

 setContentView(R.layout.full_screen);

    full_view   = (ImageView)findViewById(R.id.full_view);

    Bundle bundle=getIntent().getExtras();
    byte[] image=   bundle.getByteArray("image");


    Bitmap theImage = BitmapFactory.decodeByteArray(image, 0, image.length);
    Bitmap resized = Bitmap.createScaledBitmap(theImage,width , height, true);

    full_view.setImageBitmap(resized);

    width       =     full_view.getWidth();
    height      =     full_view.getHeight();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top