2016-02-16 65 views
1

我想修復imageview的高度,但根據不同的設備和dpi的高度。如何設置高度根據設備的dpi的寬度成正比android

<ImageView 
     android:id="@+id/imgFood" 
     android:layout_width="match_parent" 
     android:layout_height="200dp" 
     android:scaleType="centerCrop" 
     android:src="@drawable/ic_no_img" /> 

截至目前我固定高度爲200dp,但我想保持它的比例爲1:2而不是固定大小。我知道android在dp上工作,但我無法弄清楚如何保持所有設備的比例。寬度將匹配父級(適合設備寬度),但高度需要相應地更改。

任何想法/建議?

回答

5

您可以像這樣動態設置您的高度。

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth(); 

ll.getLayoutParams().height = width/2; 
ll.getLayoutParams().width = width; 
ll.requestLayout(); 
1

可以使用layout_weight屬性,例如設置高度或觀看寬度比內部LinearLayout

<LinearLayout 
    android:weightSum="3" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" > 

    <View 
     android:layout_weight="1" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" /> 

    <View 
     android:layout_weight="2" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" /> 

</LinearLayout> 

這將導致LinearLayout的內Views採取的一個,三分之二其寬度。否則,如果您必須使用不同的佈局,目前沒有辦法在.xml文件中執行此操作,並且選項將回退到以編程方式設置大小,就像在Hussnain Azam的答案中一樣(您不需要'不過總是必須要求顯示屏的大小)。

相關問題