Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I get Width View in Fragment

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?

like image 201
dmnlk Avatar asked Mar 28 '13 05:03

dmnlk


People also ask

Can a fragment have its own view?

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.

Which method is used to access the fragmented view?

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).

What is FrameLayout in fragment?

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.

What is the advantage of using fragments?

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.


1 Answers

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...

like image 81
Andrew Avatar answered Oct 20 '22 04:10

Andrew