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

时间:2012-10-15 13:43:32

标签: android imageview classcastexception layoutparams

我已将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

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

2 个答案:

答案 0 :(得分: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);

试试这个。

答案 1 :(得分:0)

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

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

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

有效。