简体   繁体   中英

Getting width of View make an exception 'Attempt to read from field on a null object reference'

I'm trying to getting a width value of TextView by

TextView textViewA = new TextView(Context);

textViewA.Text = "Test";
textViewA.Measure(LayoutParams.MatchParent, LayoutParams.WrapContent);
int width = textViewA.MeasuredWidth;
textViewA.Text = width.ToString();

The error 'Attempt to read from field 'int android.view.ViewGroup$LayoutParams.width' on a null object reference ' is occurred at textViewA.Text = width.ToString();

Addtionally, I encounter this error when I use Measure. How can I resolve it?

Since the null object appears to be width, that means textViewA.MeasuredWidth is returning null.

Have you tried using TextViewA.getMeasuredWidth() ?

The error 'Attempt to read from field 'int android.view.ViewGroup$LayoutParams.width' on a null object reference' is occurred at textViewA.Text = width.ToString();

I made a demo and reproduced the problem. It seems the text can only be changed before measure . But in your case you need to get the MeasuredWidth . So I found a workaround:

Attach your textViewA to your Activity before changing the Text:

textViewA.Measure(LayoutParams.WrapContent, LayoutParams.WrapContent);
var root = FindViewById<LinearLayout>(Resource.Id.root);
root.AddView(textViewA,LayoutParams.MatchParent);// append the textViewA to activity fix the problem
int width = textViewA.MeasuredWidth;
textViewA.Text = width.ToString();

And the error will be gone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM