2016-02-16 66 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的答案中一样(您不需要'不过总是必须要求显示屏的大小)。

相关问题