2016-01-24 28 views
0

我有RelativeLayout與weight屬性的寬度,並使用130dp高度,但它看起來像一個矩形,現在我想高度等於寬度(我想要實現以方形),這樣的形象:創建具有相同的高度和寬度的RelativeLayout時,使用重量屬性的寬度

enter image description here

這是我的xml:

<LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_margin="3dp"> 

     <RelativeLayout 
      android:layout_width="0dp" 
      android:layout_height="130dp" 
      android:layout_marginRight="2dp" 
      android:layout_weight="1" 
      android:background="#00c4ff" 
      android:onClick="blockClick"> 

     </RelativeLayout> 

     <RelativeLayout 
      android:layout_width="0dp" 
      android:layout_height="130dp" 
      android:layout_marginLeft="2dp" 
      android:layout_marginRight="2dp" 
      android:layout_weight="1" 
      android:background="#00c4ff" 
      android:onClick="blockClick"> 

     </RelativeLayout> 
    </LinearLayout> 

回答

2

讓自己實現RelativeLayoutaspect ratio ImageView

代碼示例代碼示例:

public class MyRelativeLayout extends RelativeLayout{ 

[...] 

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

    int newWidth = getMeasuredWidth(); 
    int newHeight = newWidth; 

    setMeasuredDimension(newWidth, newHeight); 
    } 

[...] 

} 
+0

和我應該在xml的relativelayout的height屬性中寫什麼? – majid

+1

'android:layout_height =「wrap_content」'這個屬性被忽略。 –

3

使用自定義的RelativeLayout ...

public class SquareRelativeLayout extends RelativeLayout { 

    public SquareRelativeLayout(Context context) { 
     super(context); 
    } 

    public SquareRelativeLayout(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public SquareRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
    } 

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

     int width = getMeasuredWidth(); 
     setMeasuredDimension(width, width); 
    } 
} 
+0

和我應該在xml中寫入relativelayout的height屬性? – majid

+1

高度屬性被這種方法忽略,所以沒關係。更好的方法是從widthMeasureSpec獲取寬度,如下所示。 int width = MeasureSpec.getSize(widthMeasureSpec) – Sfseyhan

+1

@majid你應該使用height作爲... android:layout_height =「wrap_content」 –

0

關於不同的屏幕設備的思考,有一個解決辦法:

  1. 獲取屏幕的寬度。 W¯¯
  2. 分在W:W/2
  3. 設置RelativeLayout的每一個高度與W/2

我已經使用這個解決方案設置具有不同的屏幕上的修復率的圖像視圖。

layout.width = getResources().getDisplayMetrics().widthPixels; 
    layout.height = (int) (layout.width/(2.0)); 
    mRelativeView.setLayoutParams(layout);