7

Here is my layout.I need to get the width in CategoryFragment.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/category_list"
        android:layout_width="150dp"
        android:layout_height="match_parent"
        android:background="@color/white_background"
        android:orientation="vertical" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="10dp"
            android:text="@string/pianodule_list"
            android:textSize="16sp" />

        <com.handmark.pulltorefresh.library.PullToRefreshListView
            android:id="@id/refreshable_listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:choiceMode="singleChoice"
            android:descendantFocusability="beforeDescendants"
            android:divider="@null" />
    </LinearLayout>

    <View
        android:layout_width="0.1dp"
        android:layout_height="match_parent"
        android:background="@color/divider_line" />

    <fragment
        android:name="com.srefu.frag.CategoryFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:tag="category" />
</LinearLayout>

so in onViewCreated() of CategoryFragment I try several way to achieve it but all not work.

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    View v = view;
    // View v = getView(); 
    int w1 = v.getWidth(); //return 0
    int w2 = v.getLayoutParams().width; //return NullPointerException
    int w3 = v.getMeasuredWidth(); //return 0
}

how should i do can i get width of fragment?Any help will is appreciated .Thanks. :)

Folyd
  • 1,148
  • 1
  • 16
  • 20

1 Answers1

23

you are calling getWidth() too early. Try below mentioned code. Hope it helps you

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        mScrollView.post(new Runnable() {
            public void run() {
                view.getHeight(); //height is ready
            }
        });
    }
});
Jorge Gil
  • 4,265
  • 5
  • 38
  • 57
Raj Karekar
  • 657
  • 6
  • 7
  • Fantastic,it work for me!I agree with you that i calling getWith() too early.Thanks.:) – Folyd Aug 20 '14 at 05:31
  • 1
    Don't forget to remove the globallayoutlistener once you get the height, otherwise you may have a leak. You should use removeOnGlobalLayoutListener right after getting the height, if you just need it one time. – Shibakaneki Dec 01 '19 at 14:01