Home » Android » measure() doesnt work properly with dynamic layouts and textView – Android

measure() doesnt work properly with dynamic layouts and textView – Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

I want to convert a RelativeLaout view into a Bitmap. I’ve tried another answers and different options without success.
My XML View is kind of:

----RelativeLayout
-------ImageView
-------TextView

Every ones have wrap_content measures.

As i need several bitmaps of the view, im inflating it this way:

  LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.localviewlayout, null);

ImageView img = (ImageView) v.findViewById(R.id.imgPlace);
img.setImageBitmap(MyDynamicBitmap);

TextView txt1 = (TextView)v.findViewById(R.id.text1);
txt1.setText(MyDynamicText);
return v;

After that :

//in measure() i get a nullpointerException on RelativeLayout.onMeasure().I also have tried //with MeasureSpec.EXACTLY
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap( v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
v.draw(new Canvas(b));
Paint p = new Paint();
myMainCanvas.drawBitmap(b, myPointX, myPointY, p);                   

The content of textView of the RelativeLayout is dynamic, so i cant know the width or height of the text.
Besides of the exception, if i manually set enough size on the measure function (insted of 0), my dynamic text doesnt display entirely.
I hope you can help me because right now, im stuck. Thank youuu

How to&Answers:

Try adding

v.setLayoutParams(new LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

before calling measure(). Does that fix the NullPointerException?