Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change gravity programmatically on ListView item

I would like to have a ListView in which some items render on the left, and some on the right. I don't really know how to make this happen though. I was thinking of calling setGravity(Gravity.RIGHT) on the View my adapter's getView() method returns, but that method apparently exists only for ViewGroup, which makes me think it would actually change the gravity of the object's contents. It would look something like this:

getView(int position, View toReturn, ViewGroup parent) {

    // Holder pattern, *yawn*

    if (needsToBeOnRight) {
        toReturn.setGravity(Gravity.RIGHT)

        // or whatever it is I'm actually supposed to do
    }

    return toReturn;
}

The View represented by toReturn is expected to be a RelativeLayout, so I supppose in theory I could cast it to one and try the above, but as discussed above, I doubt that will work. How should I proceed?

like image 690
sigmabeta Avatar asked Mar 16 '26 12:03

sigmabeta


1 Answers

Turns out I was almost there. In order to make it work, I had to wrap the view I want to right-or-left-orient in a FrameLayout. That would make toReturn in the above code a FrameLayout.

ViewHolder holder = (ViewHolder) toReturn.getTag();

// Get the view's LayoutParams. In this case, since it is wrapped by a FrameLayout,
// that is the type of LayoutParams necessary.
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) holder.viewThatMightNeedToBeOnRight.getLayoutParams();

// Set gravity to right or left as necessary within the LayoutParams.
if (params != null) {
    if (needsToBeOnRight) {
        params.gravity = Gravity.RIGHT;
    } else {
        params.gravity = Gravity.LEFT;
    }

    // Assign the newly edited LayoutParams to the view.
    holder.viewThatMightNeedToBeOnRight.setLayoutParams(params);
}
like image 78
sigmabeta Avatar answered Mar 18 '26 01:03

sigmabeta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!