Question

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?

Was it helpful?

Solution

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);
}

OTHER TIPS

LayoutParams lay = new LayoutParams(LayoutParams.MATCH_PARENT,
                                    LayoutParams.MATCH_PARENT);
lay.gravity      = Gravity.END;

mListView.setLayoutParams(lay);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top