2012-04-09 38 views
2

我在RelativeLayout中有一個TextView(width:fill_parent),我想要確保它是在它上面的兩個視圖下,並列,動態寬度和高度。這意味着,有時左視圖更高,有時右視圖更高。RelativeLayout - 定位項目低於兩個視圖中的最低值

我試圖設置兩個「以下」參數,但這當然是不允許的。 我試圖修改它通過代碼(與具有XML將​​其設置成txt TextView的下面和img是它旁邊的ImageView的):

if (txt.getHeight() + txt.getTop() < img.getHeight() + img.getTop()) { 
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 
        params.addRule(RelativeLayout.BELOW, R.id.image); 
        txtDetails.setLayoutParams(params); 
       } 

(txtDetails是,我想兩個視圖下面的一個)。

當沒有工作(沒有任何改變),我把txtDetails放在它自己的RelativeLayout下方的RelativeLayout中,這兩個視圖都在這兩個視圖中工作。不過,我覺得RL應該能夠處理這種情況,而不需要創建一個新的RL。可能嗎?或者定位此視圖的最佳方式是什麼?

感謝

回答

1

一個可能的問題與您的代碼:
要調用一個視圖的getHeight(),如果佈局傳遞尚未完成,可能返回0。您應該將整個代碼放在GlobalLayoutListener中,如下所示:

getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
     // your code here... 
     txt.requestLayout(); // Add this to ensure your changes are applied. 
    } 
} 

PS。你可以撥打txt.getBottom()而不是txt.getHeight() + txt.getTop()

2

爲什麼不使用tablelayout?它在2行中完全符合你的要求。

首先在一行中添加兩個變量視圖,然後添加另一行包含您的textview。

像這樣:

<TableLayout 
    android:id="@+id/center" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" > 
    <TableRow > 
    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="150sp" 
     android:layout_height="wrap_content" 
     android:text="@string/lorem_short" /> 

    <TextView 
     android:id="@+id/textView2" 
     android:layout_width="150sp" 
     android:layout_height="wrap_content" 
     android:layout_marginRight="15dp" 
     android:text="@string/lorem_long" /> 
    </TableRow> 
    <TableRow> 
    <TextView 
     android:id="@+id/textView3" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="5sp" 
     android:text="Large Text" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 
    </TableRow> 
</TableLayout>