When should I get Width View in fragment

I add View (button) programmatically in Linearlayout.LinearLayout is styled XML in Fragment.

I want to get the width of the button, but always return 0.

I was looking for this problem,

getWidth only works in WindowFocusChanged mode.

public void onWindowFocusChanged(boolean hasFocus) { } 

but fragment does not have this method.

How to get the width of a view in a fragment?

+7
source share
2 answers

Send a message to GlobalLayoutListener . You can use the listener on Button in onCreateView() , as you used onWindowFocusChanged . It is also more reliable than onWindowFocusChanged() .

Try the following:

  final View myView = profileContainer.findViewById(R.id.sub_page_padding); ViewTreeObserver vto = profilePadding.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Log.d("TEST", "Height = " + myView.getHeight() + " Width = " + myView.getWidth()); ViewTreeObserver obs = profilePadding.getViewTreeObserver(); obs.removeGlobalOnLayoutListener(this); } }); 
+8
source

I had a similar problem and it was solved in the Fragment onViewCreated () callback as follows:

 @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 () is started after all views are displayed ...

+5
source

All Articles