Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic image size for android

I am facing a problem of retaining the same layout from android phone to tablet.

The reason is because most of my images are fixed size. Thus, it will cause problem when changing from phone to tablet.

The layout of my activity is like this.

<relativelayout> - with match_parent for both width and height
     <linearlayout> - with match_parent for both width and height
          <linearlayout> - with match_parent for for width only and match_content for height
                <imageview> - fixed size - 94 dp and 32 dp

Is there a possible to do something similar to giving the width a percentage like how we did in html rather than a fix dp? so that it can auto adjust to the parent width.

Thank You!

like image 913
James Yeo Avatar asked Mar 19 '23 14:03

James Yeo


1 Answers

Please try somethings like that:

Step 1: calculate Height and width of your device screen dynamically by using this code.

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

int screenHeight = displaymetrics.heightPixels;
int screenWidth = displaymetrics.widthPixels;

Step 2: Get reference of your ImageView in your Activity or Fragment by using this code

ImageView myImageView = (ImageView) findViewById(R.id.your_image_view);

Step 3: Now calculate Height and width for Your ImageView according to Height and width of your Screen.

Suppose you want to 10% Height ImageView corresponding to screen; Then image height should be

int imgHeight = (int) (screenHeight* 0.10); // 10% of screen.

by the same way for width you want 25% then it should be:

int imgWidth =  (int) (screenWidth* 0.25); // 25% of screen.

Step 4: Finally set Height and width of your ImageView problematically by this code.

myImageView.getLayoutParams().height = imgHeight;
myImageView.getLayoutParams().width = imgWidth;

Hope it will help you. Let me know.

like image 69
Lavekush Agrawal Avatar answered Mar 27 '23 17:03

Lavekush Agrawal