GetWidth Returns 0 in the fragment, getPaddingLeft Returns Non-Zero

I am trying to convert my Android app to Fragments in order to support multiple screen sizes and correctly use the new ICS tabs. I used to use the onWindowFocusChanged() method and run the following code inside it - basically it did some dynamic formatting of my layout after it was created.

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LinearLayout theLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag2_layout, container, false); getWidthEditButton = (ImageButton) theLayout.findViewById(R.id.buttonEditPoints); buttonAddPointsManual = (ImageView) theLayout.findViewById(R.id.buttonAddPointsManual); linearPointsUsed = (LinearLayout) theLayout.findViewById(R.id.linearLayoutPointsUsed); int paddingLeftForTracker = linearPointsUsed.getPaddingLeft(); int paddingRightForTracker = getWidthEditButton.getWidth(); linearPointsUsed.setPadding(paddingLeftForTracker, 0, paddingRightForTracker, 0); } 

Now that I have switched to fragments, and for some reason my paddingRightForTracker returns 0. I encountered a problem earlier when I tried to get the width too early, so my transition to onWindowFocusChanged earlier, but this is not available for fragments. It is strange that paddingLeftForTracker actually returns a nonzero value.

If I install paddingRightForTracker manually, this change happens, so I know the code works. I just can't understand why my getWidth returns 0.

Any help would be greatly appreciated.

+7
source share
2 answers

You can try to do this in onActivityCreated (). This way you save the link to these views in onCreateView and then access them in onActivityCreated (). I think the view is not complete when you try to access it, so it does not return the width.

http://developer.android.com/reference/android/app/Fragment.html#onActivityCreated(android.os.Bundle)


Ok, so I found out about another way to get the width. I, too, cannot get the width of the button on either onViewCreated, onCreateView, or onResume. I found this, tried it, and it returns a value, so maybe this will work for you!

How to get the height and width of a button

 ViewTreeObserver vto = button.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { width = button.getWidth(); height = button.getHeight(); } }); 

FYI, I ran this code in onResume, so I'm not quite sure where else it could work.

+20
source

This works for me and it looks cleaner (I also use lambda, but this is not required):

 v.post(() -> { int width = v.getWidth(); doSomething(width>300); }); 
0
source

All Articles