How to set View Height dynamiocally based on the android device? - android

I have a view and I am measuring screen size of the device dynamically using this method.
private double getscreenSize() {
DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(
((double) (dm.widthPixels) / (double) (dm.densityDpi)), 2);
double y = Math.pow(
((double) (dm.heightPixels) / (double) (dm.densityDpi)), 2);
return Math.sqrt(x + y);
}
It returns 4.58 inch for both s3 and s4. But in s4 , the view looks too small and in s3 it looks perfect.

Use this code-
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
After getting height and width use this for your view.

Related

How to know smallest width (sw) of an android device?

I have 4 different devices:
Asus tablet, screensize 7"
Lenovo tablet, screensize 7"
HTC mobile phone, screensize 5"
HTC mobile phone, screensize 4.7"
I want to know the smallest width (sw) of my device to make a support layout for it.
I want to make a resource folder like "layout-sw600dp" but I don't know the value of the smallest width (sw).
I tried to print the sw using this code:
DisplayMetrics metrics = getResources().getDisplayMetrics();
Log.i("Density", ""+metrics.densityDpi);
but i don't know if this is the correct value.
How do I find the smallest width (sw)?
Best solution for min API 13 and above:
Configuration config = getResources().getConfiguration();
config.smallestScreenWidthDp
The last line return the SW value in dp !
Source google : http://android-developers.blogspot.fr/2011/07/new-tools-for-managing-screen-sizes.html
Here is an another easy way .
You can check the Smallest Width of the Device from Developer Options (In Android Studio Emulator & It's not found in my Real Device) .
Correction to the above answer, the right code to find the correct sw try this:
DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
float screenWidth = dm.widthPixels / dm.density;
float screenHeight = dm.heightPixels / dm.density;
whichever one of screenWidth and screenHeight is smaller is your sw.
Min api 13 and above go with #Tobliug answer- best solution.
Configuration config = getResources().getConfiguration();
config.smallestScreenWidthDp;// But it requires API level 13
Below API level 13 try this answer
Create SmallWidthCalculator.java class & just copy paste this code
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
public class SmallWidthCalculator {
private static SmallWidthCalculator ourInstance = new SmallWidthCalculator();
public static SmallWidthCalculator getInstance() {
return ourInstance;
}
private Context mContext;
private SmallWidthCalculator() {
}
public double getSmallWidth(Context context) {
mContext = context;
DisplayMetrics dm = context.getResources().getDisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;
double dpi = getDPI(width, height);
double smallWidthDPI = 0;
int smallWidth = 0;
if (width < height)
smallWidth = width;
else
smallWidth = height;
smallWidthDPI = smallWidth / (dpi / 160);
return smallWidthDPI;
}
private double getDPI(int width,
int height) {
double dpi = 0f;
double inches = getScreenSizeInInches(width, height);
dpi = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)) / inches;
return dpi;
}
private double getScreenSizeInInches(int width, int height) {
if (mContext != null) {
DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
double wi = (double) width / (double) dm.xdpi;
double hi = (double) height / (double) dm.ydpi;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
return Math.sqrt(x + y);
}
return 0;
}
}
From your activity or Fragment just pass your context and get your small Width
double smallWidthDp=SmallWidthCalculator.getInstance().getSmallWidth(this);
you can try this:
DisplayMetrics dm = mActivity.getApplicationContext()
.getResources().getDisplayMetrics();
float screenWidth = dm.widthPixels / dm.xdpi;
float screenHeight = dm.heightPixels / dm.ydpi;
For Details :here

Code for Android Screen Size doesn't work

I have tried the codes below for finding out the screen size but none worked for me. The interface also goes out of proportion for different devices of the same screen sizes and same dimensions. I don't have actual devices, I am using the devices with screen sizes/dimensions provided by the AVD. The codes work for dimensions but it doesn't give the correct screen size. The screen size it calculates for a 4 inch screen is 3.9 inches (round figure) and the screen size for a 3.7 inch screen is also 3.9 inches. The interface code for the Nexus S (4", 480x800: hdpi) doesn't work for the 4" WVGA (480x800: hdpi) where both have the same screen size and same dimensions.
Could you please help me solve this problem.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int widthInch=dm.widthPixels;
int heightInch=dm.heightPixels;
int dens=dm.densityDpi;
double wi=(double)widthInch/(double)dens;
double hi=(double)heightInch/(double)dens;
double x = Math.pow(wi,2);
double y = Math.pow(hi,2);
double screenInches = Math.sqrt(x+y);
screenInches = (double)Math.round(screenInches * 10) / 10;
int widthPix = (int) Math.ceil(dm.widthPixels * (dm.densityDpi / 160.0));
Toast.makeText(getApplicationContext(), width+"*"+height+" - "+widthPix+
" - " +screenInches,
Toast.LENGTH_LONG).show();
//================================================================
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
//get density per inch for example: 120 , 160 , 240
float mXDpi = metrics.xdpi; // 160 The exact physical pixels per inch of the screen in the X dimension.
float mYDpi = metrics.ydpi;
//density
int nDensity = metrics.densityDpi; // 160 screen density expressed as dots-per-inch
float mMetersToPixelsX = mXDpi / 0.0254f; // 1 inch == 0.0254 metre
float mMetersToPixelsY = mYDpi / 0.0254f;
//Resolution
//The total number of physical pixels on a screen.
int wPix = metrics.widthPixels; // 320 The absolute width of the display in pixels.
int hPix = metrics.heightPixels; // 480 The absolute height of the display in pixels.
int nWidthDisplay = (wPix < hPix)? wPix : hPix;
float nWidthScreenInInch = wPix / mXDpi; //320 / 160 == 2.0 in inch.
float nHeightScreenInInch = hPix / mYDpi; //480 / 160 == 3.0 in inch.
double screenInches = Math.sqrt( nHeightScreenInInch*nHeightScreenInInch +
nWidthScreenInInch * nWidthScreenInInch);
screenInches = (double)Math.round(screenInches * 10) / 10;
Toast.makeText(getApplicationContext(),"Screen size: "+screenInches,
Toast.LENGTH_LONG).show();
//================================================================
DisplayMetrics metrics=new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
float hgt=metrics.heightPixels/metrics.xdpi;
float wdth=metrics.widthPixels/metrics.ydpi;
double screenInches = FloatMath.sqrt(hgt*hgt+wdth*wdth);
screenInches = (double)Math.round(screenInches * 10) / 10;
Toast.makeText(getApplicationContext(),width+"*"+height+" - "+screenInches,
Toast.LENGTH_LONG).show();
//===============================================================
How to get android device screen size?
Calculating android screen size?
Detect 7 inch and 10 inch tablet programmatically
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
final int height = metrics.heightPixels;
int width = metrics.widthPixels;

How to get the Display Size in Inches in Android?

I need for my Application the exact inch of a display. My current solution is:
double inch;
double x = Math.pow(widthPix/dm.xdpi,2);
double y = Math.pow(heigthPix/dm.ydpi,2);
double screenInches = Math.sqrt(x+y);
inch = screenInches;
inch = inch * 10;
inch = Math.round(inch);
inch = inch / 10;
Is there a better way to get the display inch? Current on my test device 4 inch it say 5.9 and that is wrong...
The following gave me a a result quite close to the specs:
DisplayMetrics dm = getResources().getDisplayMetrics();
double density = dm.density * 160;
double x = Math.pow(dm.widthPixels / density, 2);
double y = Math.pow(dm.heightPixels / density, 2);
double screenInches = Math.sqrt(x + y);
log.info("inches: {}", screenInches);
Output: inches: 4.589389937671455
Specs: Samsung Galaxy Nexus (720 x 1280 px, ~320 dpi, 4.65")
Please note, that dm.heightPixels (or dm.widthPixels depending on your orientatation) does not necessarily provide accurate information, since soft keys (as used in the Galaxy Nexus) are not added to the height (or width).
Try this.... This will give you the exact size of the display..
static String getDisplaySize(Activity activity) {
double x = 0, y = 0;
int mWidthPixels, mHeightPixels;
try {
WindowManager windowManager = activity.getWindowManager();
Display display = windowManager.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
Point realSize = new Point();
Display.class.getMethod("getRealSize", Point.class).invoke(display, realSize);
mWidthPixels = realSize.x;
mHeightPixels = realSize.y;
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
x = Math.pow(mWidthPixels / dm.xdpi, 2);
y = Math.pow(mHeightPixels / dm.ydpi, 2);
} catch (Exception ex) {
ex.printStackTrace();
}
return String.format(Locale.US, "%.2f", Math.sqrt(x + y));
}

How to get android device screen size?

I have two android device with same resolution
Device1 -> resolution 480x800 diagonal screen size -> 4.7 inches
Device2 -> resolution 480x800 diagonal screen size -> 4.0 inches
How to find device diagonal screen size?
Detect 7 inch and 10 inch tablet programmatically
I have used the above link but it gives both device diagonal screen size -> 5.8
try this code to get screen size in inch
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width=dm.widthPixels;
int height=dm.heightPixels;
double wi=(double)width/(double)dm.xdpi;
double hi=(double)height/(double)dm.ydpi;
double x = Math.pow(wi,2);
double y = Math.pow(hi,2);
double screenInches = Math.sqrt(x+y);
This won't work?
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
double screenInches = Math.sqrt(x + y);
Log.d("debug", "Screen inches : " + screenInches);
Don't forget to multiply the screen size by the scaledDensity if you are doing what I did and change the size of stuff based on the screen size. e.g.:
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
double screenInches = Math.sqrt(x + y) * dm.scaledDensity;
Log.d("debug", "Screen inches : " + screenInches);
Note the second last line! Here's more info the scaledDensity stuff: What does DisplayMetrics.scaledDensity actually return in Android?
None of the above answers gave correct screen size... But the below method does it right.
private String getScreenSize() {
Point point = new Point();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRealSize(point);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int width=point.x;
int height=point.y;
double wi=(double)width/(double)displayMetrics.xdpi;
double hi=(double)height/(double)displayMetrics.ydpi;
double x = Math.pow(wi,2);
double y = Math.pow(hi,2);
return String.valueOf(Math.round((Math.sqrt(x+y)) * 10.0) / 10.0);
}
Note: This works only on API 17 & above.
Try this:
public static Boolean isTablet(Context context) {
if ((context.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE) {
return true;
}
return false;
}
DisplayMetrics displayMetrics = context.getResources()
.getDisplayMetrics();
String screenWidthInPix = displayMetrics.widthPixels;
String screenheightInPix = displayMetrics.heightPixels;
Pythagoras theorem to find the diagonal size of Android phone/tablet screen, same principal can be applied to iPhone or Blackberry screen.
Try as below the other way:
DisplayMetrics met = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(met);// get display metrics object
String strSize =
new DecimalFormat("##.##").format(Math.sqrt(((met.widthPixels / met.xdpi) *
(met.widthPixels / met.xdpi)) +
((met.heightPixels / met.ydpi) * (met.heightPixels / met.ydpi))));
// using Dots per inches with width and height

How to convert text width in pixels to percent of screen width/height?

I am measuring a string text to see if I should add a \n for wrapping.
I am using the Paint.measureText function, and it works most of the time but it occurs to me that this isn't accurate since a px doesn't equal a dp - I've seen online how to convert pixels to dp, but instead what I would rather do is convert px to a percentage of the screen size for example
If a is 8 pixels wide, how would I say:
float LetterWidthPercent = _______ //get width of character in percent of screen width
float LetterHeightPercent = _______ //get height of character in percent of screen height
This way I could just see:
if (LineOfTextWidth >= ScreenWidth * 0.9f) //90%
This would be an extremely useful function to have handy.
You will need to get the screen width through DisplayMetrics or how ever...
For getting the character size use paint with bounds to calculate.
characterWidth/screenWidth = characterScreenPercentage
I made it a double but you can easily change it to a float.
For Characters:
public Double characterToScreenWidthPercentage(Character c) {
Paint paint = new Paint();
Rect boundA = new Rect();
DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay().getMetrics(metrics);
paint.getTextBounds(Character.toString(c), 0, 1, boundA);
Log.v("fn", Integer.toString(boundA.width()));
Log.v("fn", Integer.toString(metrics.widthPixels));
Log.v("fn", Double.toString((float) boundA.width() / (float) metrics.widthPixels));
return ((double) boundA.width() / (double) metrics.widthPixels);
}
For strings:
public Double stringToScreenWidthPercentage(String str) {
Paint paint = new Paint();
Rect boundA = new Rect();
DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay().getMetrics(metrics);
paint.getTextBounds(str, 0, 1, boundA);
Log.v("fn", Integer.toString(boundA.width()));
Log.v("fn", Integer.toString(metrics.widthPixels));
Log.v("fn", Double.toString((float) boundA.width() / (float) metrics.widthPixels));
return ((double) boundA.width() / (double) metrics.widthPixels);
}
public static double measureWeightPercent(Context context, String textToMeasure) {
DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay().getMetrics(metrics);
TextView view = new TextView(context);
view.setText(textToMeasure);
view.measure(metrics.widthPixels, metrics.heightPixels);
double textWidth = view.getMeasuredWidth();
return textWidth / (metrics.widthPixels / 100);
}
You can measure a TextView with text inside before(or instead) drawing it on a screen. At this way you can set any font or textSize for TextView and always know how many percents the text will have on the screen.
You can use following methods to convert do to pixel and pixel to dp.
Convert dp to pixel:
public int dpToPixel(int dp) {
DisplayMetrics dm= getContext().getResources().getDisplayMetrics();
int pixel = Math.round(dp * (dm.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return pixel
}
Convert pixel to dp:
public int pixelToDp(int pixel) {
DisplayMetrics dm = getContext().getResources().getDisplayMetrics();
int dp = Math.round(pixel / (dm.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return dp;
}

Categories

Resources