1

I have set a Bitmap to an ImageView and then want to set wrap_content for both width and height.

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

It is giving java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams

What is the problem in my code? How to solve?

dev_android
  • 8,698
  • 22
  • 91
  • 148
  • What is the type of imgSubsegmentSensor? Have you tried Project -> Clean? – Rajesh Oct 15 '12 at 13:48
  • 1
    Read the exception... `java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams` - you need a `ViewGroup.MarginLayoutParams` –  Mar 12 '14 at 14:23

2 Answers2

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

Try this.

petey
  • 16,914
  • 6
  • 65
  • 97
0
FrameLayout.LayoutParams imageViewParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);

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

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

It works.

dev_android
  • 8,698
  • 22
  • 91
  • 148
  • I have a custom ImageView in which I am zooming, moving and rotating the image. And in main activity I am making Imageviews dynamically. When I applied your method, my imageview is not showing. Note: I have set the "ScaleType" to "Matrix". Please guide me. – Vikrant_Dev Jan 15 '14 at 14:12