mattdonders
mattdonders

Reputation: 1356

getWidth Returns 0 in Fragment, getPaddingLeft Returns Non-Zero

I am trying to convert my Android app to Fragments to support multiple screen sizes and to use the new ICS tabs correctly. Previously I used the onWindowFocusChanged() method and ran the following code inside of it - basically this 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 moved to Fragments and for some reason my paddingRightForTracker returns 0. I ran into an issue previously where I was trying to get width too early, hence my move to onWindowFocusChanged previously, but that is not available to Fragments. The strange thing is that paddingLeftForTracker actually returns a non-zero value.

If I set paddingRightForTracker manually, the change takes place so I know the code is running. Just can't figure out why my getWidth is returning 0.

Any help would be greatly appreciated.

Upvotes: 7

Views: 9240

Answers (2)

TacoEater
TacoEater

Reputation: 2278

This works for me and it looks cleaner (I am also using lambda but it's not required):

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

Upvotes: 1

leenephi
leenephi

Reputation: 900

You could try doing it in onActivityCreated(). So, you would save a reference to those views in onCreateView, and then access them in onActivityCreated(). I think the view isn't completed created when you're trying to access it, which is why it returns no 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 a button width on neither onViewCreated, onCreateView, nor onResume. I found this, tried it, and it's returning a value, so maybe it'll work for you!

How to get height and width of 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 exactly sure where else it could work.

Upvotes: 22

Related Questions