Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Height and Width of FrameLayout based on Bitmap

I'm trying to set the FrameLayout's width and height based on a Bitmap, what I did was below

        Bitmap theBitmap = BitmapFactory.decodeFile(theFileImage.toString());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(theBitmap.getWidth(), theBitmap.getHeight());
        frame.setLayoutParams(lp);
        image.setLayoutParams(lp);
        image.setImageBitmap(theBitmap);

but I'm getting a ClassCastException.

What did I do wrong?

Edited:

java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
like image 596
Lawrence Gimenez Avatar asked Aug 30 '12 08:08

Lawrence Gimenez


1 Answers

For setting Layout params, you need to use the inner class LayoutParams of its parent.

For Example : If you are having a LinearLayout inside RelativeLayout and if you need to set the layout params of Linear Layout, you need to use the LayoutParams inner class of RelativeLayout. Else it will gives a ClassCastException.

So in your case, for setting the FrameLayout's Layoutparams , you need to use its parent Layout's Layout Params. Suppose if your layout is like :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<FrameLayout
    android:id="@+id/flContainer"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</FrameLayout>

</RelativeLayout>

Code :

    FrameLayout frame=(FrameLayout) findViewById(R.id.flContainer);  
    ImageView image=(ImageView) findViewById(R.id.image);
    Bitmap theBitmap = BitmapFactory.decodeFile(theFileImage.toString());
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(theBitmap.getWidth(), theBitmap.getHeight());
    frame.setLayoutParams(lp);
    image.setImageBitmap(theBitmap);
like image 131
Eldhose M Babu Avatar answered Sep 27 '22 21:09

Eldhose M Babu