2

I have a Fragment which contain a TextView call as mTextView. I want to get height of mTextView after append content to it in onCreateView of Fragment like this:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        final View view = inflater.inflate(
                R.layout.myfragment, container, false);

        mTextView = (TextView) view.findViewById(R.id.myTextView);
               int mHeight=mTextView.getHeight();

 }

but it's always return 0 value.

StarsSky
  • 6,721
  • 6
  • 38
  • 63
Han Tran
  • 2,073
  • 4
  • 22
  • 37
  • 2
    Give it a try using the below link, http://adanware.blogspot.in/2012/06/android-getting-measuring-fragment.html – Andro Selva Jul 02 '12 at 08:46

3 Answers3

0

Do you try to get it after

setContentView(R.layout.your_layout); 

right?

Stefano Ortisi
  • 5,288
  • 3
  • 33
  • 41
0

If you try to get the height just after onCreate, you won't be able to get because still the window is not focused. Try like this :

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    // your code here
    int mHeight=mTextView.getHeight();
}
Daud Arfin
  • 2,499
  • 1
  • 18
  • 37
  • I don't see the method onWindowFocusChanged in my fragment class :( – Han Tran Jul 02 '12 at 08:30
  • oh then you need to use message handler to get the correct height. Set a message handler inside your fragment class at a delay of 1 sec once handler fired try inside handler to get the height. If you still not able to get let me know.. – Daud Arfin Jul 02 '12 at 08:37
  • I think so but I think it's not a good solution to resolve this problem :( – Han Tran Jul 02 '12 at 08:42
  • yea but for getting height at least view should be focused on the screen and it takes some time, you just can't call the next line of set view to get the height. – Daud Arfin Jul 02 '12 at 08:46
0

The reason the View's dimentions are 0 is because when you are querying them, the view still haven't performed the layout and measure steps. You only told the view how it would "behave" in the layout, but it still didn't calculated where to put each view.

There are a few tricks to get that size though. You can use this question as a starting point although I don't like the accepted answer's approach very much.

How to get the width and height of an android.widget.ImageView?

Community
  • 1
  • 1
Pedro Loureiro
  • 11,436
  • 2
  • 31
  • 37