在ListView项目上以编程方式更改重力

时间:2014-03-10 20:36:22

标签: android android-listview gravity

我想要一个ListView,其中一些项目在左侧呈现,一些项目在右侧呈现。我真的不知道怎么做到这一点。我想在setGravity(Gravity.RIGHT)我的适配器的View方法返回时调用getView(),但该方法显然仅存在于ViewGroup,这让我觉得它实际上会改变引力对象的内容。它看起来像这样:

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

View所代表的toReturn预计会是RelativeLayout,所以我理论上我可以把它投入其中并尝试上述内容,但如上所述,我怀疑那可行。我该怎么办?

2 个答案:

答案 0 :(得分:2)

原来我几乎就在那里。为了使它工作,我不得不在FrameLayout中将我想要的视图包装在右或左方向。这会使上面代码中的toReturn成为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);
}

答案 1 :(得分:0)

for(Map.Entry e : map.entrySet())
{
    System.out.println(e.getKey() + " = "+ e.getValue());
}