junep
junep

Reputation: 2164

Getting Height of TextView before render it in layout

First, I'm write code in Xamarin for Android app.

What I've tried is this.

frame.AddView(background, LayoutParams.MatchParent, textViewA.Height);
frame.AddView(textViewA, LayoutParams.MatchParent, LayoutParams.WrapContent);

1) background is View that have background.

2) after frame(instance of FrameLayout) is set, I add this layout to TableRow

The problem is it. Since value of textViewA.Height is 0, I can't see the background. enter image description here

If I change textViewA.Height to LayoutParams.WrapContent or LayoutParams.MatchParent, then the background cover the hole page.

enter image description here

And If I change textViewA.Height to 15, background cover a part of textView.

enter image description here

So, (I think) I have to know the size of textViewA's height value to make show the background. How to do it? help me.

Upvotes: 0

Views: 481

Answers (1)

Mike Ma
Mike Ma

Reputation: 2027

I have to know the size of textViewA's height value to make show the background. How to do it?

We can not get the TextView's height directly, because the TextView might not even been measured by that time.

If you really want to get the textViewA's height please try the following code

ViewTreeObserver vto =  textViewA.ViewTreeObserver;
vto.GlobalLayout += (sender, args) =>
{
    myTextViewHeight = textViewA.Height;
};

But you measure the textViewA in the FrameLayout. When you get the "myTextViewHeight" your layout has been measured. You will still get the 0 height before you add it in the FrameLayout

As a workaround

  1. you can set "textViewA.Height" before you add in FrameLayout

  2. you can add your background as default:

    frame.AddView(textViewA, LayoutParams.MatchParent, LayoutParams.WrapContent);
    frame.AddView(background);
    

By the way, if you just need to set the background of your tablerow ,Adding textview in your tablerow with background or just setting the tablerow background could be a better choice.

Upvotes: 2

Related Questions