【问题标题】:Android Set wrap_content to ImageView by java code probAndroid通过java代码prob将wrap_content设置为ImageView
【发布时间】:2012-10-16 13:42:14
【问题描述】:

我已将 Bitmap 设置为 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

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

【问题讨论】:

  • imgSubsegmentSensor 的类型是什么?您是否尝试过 Project -> Clean?
  • 读取异常...java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams - 你需要一个ViewGroup.MarginLayoutParams

标签: android imageview classcastexception layoutparams


【解决方案1】:
    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);

试试这个。

【讨论】:

    【解决方案2】:
    FrameLayout.LayoutParams imageViewParams = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.WRAP_CONTENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT);
    
    .................
    
    imgSubsegmentSensor.setImageBitmap(bmpSubsegmentSensor);
        imgSubsegmentSensor.setLayoutParams(imageViewParams);
    

    有效。

    【讨论】:

    • 我有一个自定义 ImageView,我在其中缩放、移动和旋转图像。在主要活动中,我正在动态制作 Imageviews。当我应用你的方法时,我的 imageview 没有显示。注意:我已将“ScaleType”设置为“Matrix”。请指导我。
    猜你喜欢
    • 1970-01-01
    • 2014-11-17
    • 2017-09-23
    • 2023-03-02
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    相关资源
    最近更新 更多