簡體   English   中英

在ListView項目上以編程方式更改重力

[英]Change gravity programmatically on ListView item

我想有一個ListView,其中一些項目在左邊渲染,一些在右邊渲染。 我真的不知道怎么做到這一點。 我想在View我的適配器的getView()方法返回時調用setGravity(Gravity.RIGHT) ,但該方法顯然只存在於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中將我想要的視圖包裝在右或左方向。 這將使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);
}
LayoutParams lay = new LayoutParams(LayoutParams.MATCH_PARENT,
                                    LayoutParams.MATCH_PARENT);
lay.gravity      = Gravity.END;

mListView.setLayoutParams(lay);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM