Reputation: 6901
I would like to fix the height of imageview but according to different devices and dpi's.
<ImageView
android:id="@+id/imgFood"
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_no_img" />
As of now I fixed the height to 200dp, but I want to keep it ratio of 1:2 instead of fix size. I know android works on dp but I am unable to figure out how can i keep the ratio for all devices. Width will be match parent (fit device width) but height needs to be changed accordingly.
Any idea/suggestion?
Upvotes: 1
Views: 3619
Reputation: 4775
You can set height or width ratio of views inside LinearLayout
using the layout_weight
property, for example:
<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>
This will cause the inner Views
of the LinearLayout
to take one and two thirds of its width, respectively.
Otherwise, if you have to use a different layout, there is currently no way to do this in .xml files, and the option is to fall back to setting the size programmatically, like in Hussnain Azam's answer (you don't always have to call for size of the display though).
Upvotes: 1
Reputation: 358
You can set your height dynamically like this.
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
ll.getLayoutParams().height = width/2;
ll.getLayoutParams().width = width;
ll.requestLayout();
Upvotes: 5