Reputation: 32273
I have a Layout containing a fragment. I set width of Layout to let's say 300dip.
I want to calculate the width of the children programmatically in relation to the 300dip of the parent.
I can't do it in XML since it has some "tricks" and using weigths or RelativeLayout will not work and I have to use maths.
Here is the fragment with the containing layout...
<LinearLayout
android:layout_width="300dip"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<fragment
android:id="@+id/tabbar"
android:name="com.test.MyFragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
In MyFragment there's the method:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("test", "container: " + container);
View view = inflater.inflate(R.layout.mylayout, container, false);
Log.d("test", "view width: " + view.getWidth());
//do things with view
return view;
}
I get the outputs container: null and view width: 0 and I can't find any onMeasure method in the fragment or similar.
Upvotes: 0
Views: 7838
Reputation: 380
Use Handler will get height and width. but this is not a proper way.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.d("test", "view width: " + view.getWidth());
}
},1000);
Upvotes: 0
Reputation: 5575
onCreateView
is called before your layouts have been inflated, so they have no height
or width
. If you want to fiddle with how layouts and views
are drawn, you can create your own view, extending View
, and implement onLayout()
; If you Google, there's plenty of examples of that.
Upvotes: 1
Reputation: 963
I think you can find the dimensions of your parent view (LinearLayout) programmatically in the onActivityCreated method:
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
myActivityView = (LinearLayout)
getActivity().findViewById(((View) getView().getParent()).getId());
myFragment = (RelativeLayout) getView().findViewById(R.layout.mylayout);
//Change RelativeLayout to whatever your fragment is using
}
So then myActivityView should be your parent view.
EDIT
You could then use a ViewTreeObserver in onActivityCreated to get the dimensions of your parent view. myFragment should be your fragment, so you could place it relative to the dimensions returned from myActivityView. Good luck.
Upvotes: 0