簡體   English   中英

在Gravity.CENTER相對布局中向左對齊膨脹視圖

[英]Align inflated view left in Gravity.CENTER Relative Layout

我有一個相對的布局,它充當具有動態更改的文本內容的按鈕。 此文字使用android:gravity="center"屬性在布局中居中。 問題是我需要在同一“相對布局”中充氣另一個布局,但將其向左對齊。 我可以很好地使視圖膨脹,但是它總是顯示在中心(如預期的那樣,因為布局具有中心重力)。 看起來像這樣...

在此處輸入圖片說明

灰色框是父級相對布局,綠色框是我要向左對齊的視圖。 我嘗試過將邊距設置為各種內容-包括偏移量為父視圖寬度的一半-但到目前為止,任何方法都無法正常工作。 有沒有辦法做到這一點? 可能值得補充的是,父級相對布局(灰色框)的寬度會有所不同,因此,無論大小如何,解決方案都應該能夠正常工作。

誇大綠色視圖的XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="20dp"
          android:layout_height="fill_parent"
          android:background="@color/pending_color"
          android:paddingLeft="5dp"
          android:id="@+id/ribbon">

我將視圖擴展到父級RelativeLayout的代碼:

        View inflatedView = mLayoutInflater.inflate(R.layout.pending_ribbon, null);
    RelativeLayout.LayoutParams params = new LayoutParams(30, RelativeLayout.LayoutParams.MATCH_PARENT);
    inflatedView.setLayoutParams(params);

    this.addView(inflatedView);

因此,第一個問題是, 不要將null傳遞給inflate() 傳遞父級ViewGroup ,並傳遞false表示您尚不希望附加它:

View inflatedView = mLayoutInflater.inflate(R.layout.pending_ribbon, this, false);

完成此操作后,視圖應該已經具有LayoutParams了,您將不必手動設置它們:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParms) inflatedView.getLayoutParams();

ALIGN_PARENT_LEFT規則添加到ALIGN_PARENT_LEFT視圖中( RelativeLayout並不真正使用gravity ):

params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

然后添加視圖,您應該會很好:

addView(inflatedView);

如果我正確遵循,您有一個父視圖,該父視圖是RelativeLayout,並且需要將子1(文本視圖)居中,並將子2(線性布局)居左對齊?

嘗試:

兒童1

    android:layout_centerInParent="true"
    or
    android:layout_centerHorizontal="true" 

兒童2

    android:layout_alignParentLeft="true"

編輯:

您可以將子級2封裝在另一個RelativeLayout中

    parentlayout
        child1
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >
            <child2
                android:layout_alignParentLeft="true">
        </RelativeLayout>

暫無
暫無

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

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