2014-10-06 109 views
0

我有一個相對佈局,充當一個動態更改文本內容的按鈕。此文本使用android:gravity="center"屬性在佈局中居中。問題是我需要在相同的相對佈局內膨脹另一個佈局,但將其對齊到左側。我可以誇大視圖,但它總是顯示在中心(因爲佈局具有中心重力,所以可以預期)。它看起來像這樣...在Gravity.CENTER相對佈局中對齊左側的充氣視圖

enter image description here

灰色方塊是父相對佈局,綠色框是我想左對齊的視圖。我已經嘗試將邊距設置爲各種東西 - 包括父視圖寬度的一半左側的偏移量 - 但目前爲止沒有任何工作。有沒有辦法做到這一點?值得一提的是,父親相對佈局(灰色框)的寬度會有所不同,所以無論大小如何,解決方案都應該最好工作。綠色鑑於

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

回答

2

所以,第一個問題,don't pass null to inflate()。通過在父ViewGroup,並false,表示你不想附上它尚未:

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

一旦你做到了這一點,認爲應該已經有了的LayoutParams,你將不必進行手動設置:

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

添加ALIGN_PARENT_LEFT規則,你的膨脹視圖(RelativeLayout並沒有真正使用gravity):

params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); 

然後添加視圖,你應該很好去:

addView(inflatedView); 
+0

啊,這是做到了。非常感謝你的幫助! – rpm 2014-10-06 20:04:03

0

如果我按照正確的,你有一個父視圖這是一個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> 
+0

我試過了,它不起作用。問題是父視圖(相對佈局)已經集中了重力,並且這個重力也需要能夠動態設置。因此,以父視圖的重心爲中心,我無法讓子視圖以不同的方式對齊。 – rpm 2014-10-06 15:53:20

+0

我扔了一個編輯我的答案,可能有幫助嗎? – 2014-10-06 17:19:46