1

I have a ScrollView with some layouts in it, called the fragment_about_sl.xml.And the class associated to it is called AboutSLFragment.java.I want to calculate the height of the scrollView to get height ratio for an image.I researched the web and found this code.

ViewTreeObserver vto = scrollView.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
@Override 
public void onGlobalLayout() { 
scrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

int scrollViewHeightInPixels = layout.getMeasuredHeight(); 

//This is equal with %45 weight you tried before
int height = (scrollViewHeightInPixels * 45) / 100;
ViewGroup.LayoutParams pagerParams = viewPager.getLayoutParams();
pagerParams.height = height;
} 
});

As shown in the above code.It just have said scrollView instead of getting it from findViewById().And also in the below code,it just says layout.getMeasuredHeight() instead of specifying the name of layout.

int scrollViewHeightInPixels = layout.getMeasuredHeight(); 

The question is that I want to know what is meant by layout here(above).What should I put there,is it the id of the scrollView?If so I developed a code myself and I want to know whether it is correct.Please help me I am new to android.The id of the scrollview I used is aboutslscrollview.

final View view = rootView.findViewById(R.id.aboutslscrollview);
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        view.getViewTreeObserver().removeOnGlobalLayoutListener(this);

        int scrollViewHeightInPixels = view.getMeasuredHeight();

        //This is equal with %45 weight you tried before
        int height = (scrollViewHeightInPixels * 45) / 100;
        ViewGroup.LayoutParams pagerParams = viewPager.getLayoutParams();
        pagerParams.height = height;
    }
});
Abdul Kawee
  • 2,687
  • 1
  • 14
  • 26
C. Chan
  • 57
  • 5
  • 2
    Possible duplicate of [Android: Total height of ScrollView](https://stackoverflow.com/questions/3609297/android-total-height-of-scrollview) – AskNilesh Feb 21 '18 at 10:59
  • From which site you find that code? – Vidhi Dave Feb 21 '18 at 11:03
  • In this line `view.getViewTreeObserver().removeOnGlobalLayoutListener(this);` this view is scrollView in above code change that first. – Vidhi Dave Feb 21 '18 at 11:07
  • Hello Vishva, do you mean like this, rootView.findViewById(R.id.aboutslscrollview).getViewTreeObserver().removeOnGlobalLayoutListener(this); – C. Chan Feb 21 '18 at 14:46
  • also Vishva in this line of code, int scrollViewHeightInPixels = layout.getMeasuredHeight(); what is meant by layout, what should i put here, is it the id of the scrollView as well – C. Chan Feb 21 '18 at 14:48

0 Answers0