2014-09-10 95 views
1

我搜索了很多,以找出它的工作原理,我什麼都沒有。 我發現一些Java代碼動態地做到這一點,但沒有工作主題的螞蟻,當打開程序,顯示一個力量關閉。 這是我的代碼:如何設置relativelayout高度等於它的寬度?

<LinearLayout android:baselineAligned="false" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 

    <RelativeLayout 
     android:id="@+id/rlv1" 
     android:layout_width="match_parent" 
     android:layout_height="150dp" 
     android:layout_weight="1" 
     android:background="@drawable/rectengle2" > 
    </RelativeLayout> 

    <RelativeLayout 
     android:id="@+id/rlv2" 
     android:layout_width="fill_parent" 
     android:layout_weight="1" 
     android:background="@drawable/rectengle" > 
    </RelativeLayout> 
</LinearLayout> 

,你可以看到我創建了一個矩形形狀,並用lineaer佈局父用它在一個相對佈局和我分裂該線性佈局verticali兩個部分的每個相對佈局。 現在我想要設置這些相對的佈局高度等於它的寬度來得到一個純正方形的矩形。 我嘗試了很多方法,但...可以幫助我的任何人嗎? thnaks ..

回答

1

最後我自己發現了什麼在這種情況下做的。所以我會解釋如何解決那些有或將會有我的問題的人。 在我的xml ui文件中,我設置了layout_weight = 1的一對相對佈局,它們在線性佈局中被分割到屏幕中,實際上它們的寬度都是我的屏幕寬度的一半。我的問題是關於高度,我嘗試了很多java代碼來設置等於其寬度的相對佈局高度。 最後我計算了「DP」術語中的屏幕寬度,並將每個相對佈局的高度設置爲此。這是解決的代碼:

Display display = getWindowManager().getDefaultDisplay(); 
    DisplayMetrics outMetrics = new DisplayMetrics(); 
    display.getMetrics(outMetrics); 

    float density = getResources().getDisplayMetrics().density;   
    float dpWidth = outMetrics.widthPixels/density; 

    RelativeLayout Rl1 = (RelativeLayout) findViewById(R.id.rlv1); 
    Rl1.getLayoutParams().height = (int) (dpWidth); 

    RelativeLayout Rl2 = (RelativeLayout) findViewById(R.id.rlv2); 
    Rl2.getLayoutParams().height = (int) (dpWidth); 

所以我得到了一個純正的廣場!好好享受。謝謝

4

最簡單的解決方案,即imo,是子類的RelativeLayout,並覆蓋onMeasure,提供給超級相同的寬度和高度的大小。例如

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    super.onMeasure(widthMeasureSpec, widthMeasureSpec); 
} 

由@ZakTaccardi指出,聲明它在你的佈局像

<com.example.subclassrelativelayout 
android:layout_width="match_parent" 
android:layout_height="wrap_content" /> 
+0

我不知道如何使用。我應該如何在你寫的代碼中調用我的佈局? – mohammadf255 2014-09-10 16:22:04

+3

這是更好的答案。 您可以在XML中使用完全限定的類名引用新的子類。因此,而不是'',使用'' – ZakTaccardi 2015-02-11 00:28:20

+0

@ZakTaccardi爲您的輸入 – Blackbelt 2015-05-28 19:26:04

相關問題