gpt4 book ai didi

android - 以编程方式更改 ListView 项目的引力

转载 作者:太空狗 更新时间:2023-10-29 13:25:05 26 4
gpt4 key购买 nike

我想要一个 ListView,其中一些项目呈现在左侧,一些呈现在右侧。我真的不知道如何做到这一点。我正在考虑在 View 上调用 setGravity(Gravity.RIGHT) 我的适配器的 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;
}

toReturn 表示的 View 应该是一个 RelativeLayout,所以我假设理论上我可以将它转换为一个并尝试上面,但如上所述,我怀疑这会奏效。我应该如何进行?

最佳答案

原来我快到了。为了使其工作,我必须将我想要在 FrameLayout 中向右或向左定向的 View 包装起来。这将使上面代码中的 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);
}

关于android - 以编程方式更改 ListView 项目的引力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22310772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com