根据位图设置FrameLayout的高度和宽度

12

我正在尝试根据Bitmap设置FrameLayout的宽度和高度,我所做的是:

        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);

但是我遇到了一个 ClassCastException 错误。

我做错了什么?

编辑:

java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams

这只是一个猜测,但尝试将“LinearLayout.LayoutParams lp”更改为“RelativeLayout.LayoutParams”。 - twigg
2个回答

15

要设置布局参数,需要使用其父布局的内部类LayoutParams。

例如:如果你在RelativeLayout中有一个LinearLayout,并且你需要设置LinearLayout的布局参数,你需要使用RelativeLayout的LayoutParams内部类。否则会引发ClassCastException异常。

所以在你的情况下,要设置FrameLayout的LayoutParams,你需要使用其父布局的LayoutParams。假设你的布局如下:

<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>

代码:

    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);

现在我遇到了这个错误。严重异常:主要 08-30 17:50:24.387: E/AndroidRuntime(5325): 在android.view.ViewRoot.performTraversals(ViewRoot.java:941) - Lawrence Gimenez
如果您的图像视图位于帧布局中,请尝试删除设置图像视图布局参数的代码。检查更新后的答案并告诉我。 - Eldhose M Babu
FrameLayout的布局完美地适配了位图。 - Lawrence Gimenez
问:我该如何将图像设置为LinearLayout的图像?https://dev59.com/f2445IYBdhLWcg3wia2V(请帮忙...谢谢) - Si8

1

看到 ClassCastException,我猜测你在这里做了一些非法的事情,有几个问题,frameimage 是什么?

如果 frame 是指 FrameLayout 的引用,则必须使用:

FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(theBitmap.getWidth(), theBitmap.getHeight());

如果有帮助,请告诉我。


frame 是一个 FrameLayout,而 image 是一个 ImageView。 - Lawrence Gimenez
你的主容器布局是FrameLayout还是LinearLayout? - Arif Nadeem
父布局是RelativeLayout,FrameLayout是它的子布局,而ImageView是FrameLayout的子布局。 - Lawrence Gimenez
我还遇到了一个新的错误:FATAL EXCEPTION: main 08-30 17:35:54.148: E/AndroidRuntime(32516): at android.view.ViewRoot.performTraversals(ViewRoot.java:941) - Lawrence Gimenez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接