Android通过java代码prob将wrap_content设置为ImageView

标签 android imageview classcastexception layoutparams

我已经将位图设置为 ImageView,然后想为宽度和高度设置 wrap_content。

imgSubsegment = (ImageView) findViewById(R.id.subsegment);

ViewGroup.LayoutParams imageViewParams = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

......................................

imgSubsegmentSensor.setImageBitmap(bmpSubsegmentSensor);
imgSubsegmentSensor.setLayoutParams(imageViewParams);

它给出 java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams

我的代码有什么问题?如何解决?

最佳答案

    imgSubsegment = (ImageView) findViewById(R.id.subsegment);

    ViewGroup.MarginLayoutParams imageViewParams = new ViewGroup.MarginLayoutParams(
        ViewGroup.MarginLayoutParams.WRAP_CONTENT,
        ViewGroup.MarginLayoutParams.WRAP_CONTENT);

    ......................................

    imgSubsegmentSensor.setImageBitmap(bmpSubsegmentSensor);
    imgSubsegmentSensor.setLayoutParams(imageViewParams);

试试这个。

关于Android通过java代码prob将wrap_content设置为ImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12896919/

相关文章:

java - 反序列化抛出 java.lang.ClassCastException

android - Flutter google play 说应用程序已在 Debug模式下登录

android - 无法使用 Kotlin Jetpack Compose 从一开始就在 Android Studio 中运行任何应用程序

android - 如何动态地将 ImageView 添加到 View

android - 我如何在android中开发带有图像的PagerSlidingTabStrip?

Activity 启动时出现android classcastexception

访问 asp.net Web API 时 android 中的 java.net.MalformedURLException

java - 从 Android 应用程序的操作栏中选择菜单选项时,将数据从一个 Activity 传递到另一个 Activity

android - 大于屏幕分辨率的 ImageView 重新缩放错误

java - 通过 EventObject 的 Getter 和 Setter - ClassCastException 同一类 (Java)