I adding View (button) programally in Linearlayout.LinearLayout is layouted by XML in Fragment.
I want to get button width, but always return 0.
I googled this problem,
getWidth work only onWindowFocusChanged.
public void onWindowFocusChanged(boolean hasFocus) { }
but Fragment do not have this method.
How to get View width in Fragment?
Fragments cannot live on their own--they must be hosted by an activity or another fragment. The fragment's view hierarchy becomes part of, or attaches to, the host's view hierarchy.
onStart() makes the fragment visible to the user (based on its containing activity being started). onResume() makes the fragment begin interacting with the user (based on its containing activity being resumed).
FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other.
The Fragment class in Android is used to build dynamic User Interfaces and should be used within the activity. The biggest advantage of using fragments is that it simplifies the task of creating UI for multiple screen sizes. An activity can contain any number of fragments.
I'd had a similar problem and solved it in the Fragment callback onViewCreated() like this:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.post(new Runnable() {
@Override
public void run() {
// do operations or methods involved
// View.getWidth(); or View.getHeight();
// here
}
});
}
run() runs after all views were rendered...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With