I am noob in android. My problem about useable height of 18:9 devices.
When I try to get useable screen in these aspect-ratio my application is woking fine all android devices but when ı compile in Samsung Galaxy s8 it is not working.
I am trying to get useable screen of devices.
I have already tried method which in these links
https://stackoverflow.com/questions/43628047/how-to-support-189-aspect-ratio-in-android-apps
https://android-developers.googleblog.com/2017/03/update-your-app-to-take-advantage-of.html
And I use dynamically
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
width = metrics.widthPixels;
height = metrics.heightPixels ;
And I tried
private int getSoftButtonsBarHeight() {
// getRealMetrics is only available with API 17 and +
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int usableHeight = metrics.heightPixels;
getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
int realHeight = metrics.heightPixels;
if (realHeight > usableHeight)
return realHeight - usableHeight;
else
return 0;
}
return 0;
}
And when I try to set params MATCH_PARENT height it is working good. But I need to find useable height pixel to desing my other views proportionally .
Actually these code DisplayMetrics metrics = this.getResources().getDisplayMetrics();
height = metrics.heightPixels ; working in my Activity but when I try to use it in another window which I extend from FramaLayout and add to activity it is not working.
Here is my code block
public class StudentLoginActivity extends Activity { ...
FrameLayout.LayoutParams containerParams = new ScrollView.LayoutParams(width, height-sb);
container = new FrameLayout(this);
container.setLayoutParams(containerParams);
container.setBackgroundColor(Color.rgb(248,248,248));
loginStudentView = new StudentLoginView(this);
container.addView(loginStudentView); ...
}
public class StudentLoginView extends FrameLayout { ...
FrameLayout.LayoutParams cp = new FrameLayout.LayoutParams(width, height);
setLayoutParams(cp); ...
}
But this problem related with android navigationBar height because when I show navigation bar there is no problem but if I hide navigationBar it is not resize application still working that there is a navigation bar on screen (but I hide the navigationBar).
My problem is very similar this link
android Navigation Bar hiding and persantage of usable screen overlap
You can get the useable height (even on Galaxy S8 with or without shown NavBar) with the decorview:
//Get the correct screen size even if the device has a hideable navigation bar (e.g. the Samsung Galaxy S8)
View decorView = getWindow().getDecorView(); //if you use this in a fragment, use getActivity before getWindow()
Rect r = new Rect();
decorView.getWindowVisibleDisplayFrame(r);
int screenHeight = r.bottom; // =2220 on S8 with hidden NavBar and =2076 with enabled NavBar
int screenWidth = r.right; // =1080 on S8
If you have a view that is set to match the parent width and height (the whole screen), you can attach a listener to that view and then get its width and height.
View myView = findViewById(R.id.my_view);
myView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight,
int oldBottom) {
// its possible that the layout is not complete in which case
// we will get all zero values for the positions, so ignore the event
if (left == 0 && top == 0 && right == 0 && bottom == 0) {
return;
}
// Do what you need to do with the height/width since they are now set
}
});
This answer was taken from here.
Related
My application is cut off from the top side by the notch
Is there any specific solution to overcome this problem.
I am using the emulator Pixel 3 XL API 27
image for illustrstion
What should I do any code is there to increase the height of the top bar or status bar or should I increase the height of the title bar, but the title bar is still cut off
Any suggestion or code explanation
Try below solution
It is get size of notch as per device and set margin top to view So,it's fit in all device.
#Override
protected void onCreate(Bundle savedInstanceState) {
this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
this.getWindow().setStatusBarColor(Color.TRANSPARENT);
super.onCreate(savedInstanceState);
setContentView(MainActivity.this, R.layout.activity_main);
/*------------ Check display cutout size and give top margin to toolbar -------------*/
setMarginTopAccordingDisplayCutout(context, yourTopMainView, convertDpToPixel(34), 0);
/*-----------------------------------------------------------------------------------*/
...
//your Code
}
private void setMarginTopAccordingDisplayCutout(Context context, View view, int extraTopWithoutCutout, int extraTopWithCutout) {
int statusBarHeight = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
}
if (statusBarHeight > convertDpToPixel(24)) {
final ViewGroup.MarginLayoutParams[] layoutParams = new ViewGroup.MarginLayoutParams[1];
layoutParams[0] = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
layoutParams[0].topMargin = statusBarHeight + extraTopWithCutout;
view.setLayoutParams(layoutParams[0]);
//topbarlp.setMargins(0, statusBarHeight, 0, 0);
//Set above layout params to your layout which was getting cut because of notch
///topbar.setLayoutParams(topbarlp)
Log.e(TAG, "onCreate statusBarHeight :: " + statusBarHeight);
} else {
final ViewGroup.MarginLayoutParams[] layoutParams = new ViewGroup.MarginLayoutParams[1];
layoutParams[0] = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
layoutParams[0].topMargin = extraTopWithoutCutout;
view.setLayoutParams(layoutParams[0]);
}
}
private int convertDpToPixel(float dp) {
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return Math.round(px);
}
I hope this can help you!
Thank You.
In an Android Application, I want to know the height and the width of the screen. I'm using the following code:
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
The problem is than when the soft navigation bar exists, the returned height = the actual height - navigation bar height.
I want to get the total value.
Note: I'm using Android SDK 13 (v 3.2).
Check this, it may help:
FrameLayout root = (FrameLayout) findViewById(R.id.root);
root.post(new Runnable() {
public void run() {
Rect rect = new Rect();
Window win = getWindow(); // Get the Window
win.getDecorView().getWindowVisibleDisplayFrame(rect);
// Get the height of Status Bar
int statusBarHeight = rect.top;
// Get the height occupied by the decoration contents
int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
// Calculate titleBarHeight by deducting statusBarHeight from contentViewTop
int titleBarHeight = contentViewTop - statusBarHeight;
// By now we got the height of titleBar & statusBar , Now lets get the screen size
int screenHeight = dm.heightPixels;
// Now calculate the height that our layout can be set If you know that your application doesn't have statusBar added, then don't add here also.
//Same applies to application bar also
int layoutHeight = screenHeight - (titleBarHeight + statusBarHeight);
}
});
You can use
display.getRealSize(size); instead of display.getSize(size);
source:
http://developer.android.com/reference/android/view/Display.html#getRealSize(android.graphics.Point)
you can use DisplayMetrics. This class holds information about the screen such its size, density, font scaling. For instance
getResources().getDisplayMetrics().widthPixels
returns
The absolute width of the display in pixels.
to retrieve the height
getResources().getDisplayMetrics().heightPixels
In onCreate method of your class write down this code, and you will get the actual width and height of screen:
Display mDisplay = this.getWindowManager().getDefaultDisplay();
final int width = mDisplay.getWidth();
final int height = mDisplay.getHeight();
System.out.println("width " + width + " height " + height);
I want to insert a GraphView into a LinearLayout to show it ( graph ) on the screen and because of GraphView limitations I can't use android:layout_height="wrap_content" for my LinearLayout so I'm going to use LinearLayout.setScaleY code to make GraphView fill the screen.
now, I want to ask :
--- Is there any better way to make LinearLayout fill the screen without android:layout_height="wrap_content" code ?
If not, how can I get the activity's real usable height to use it in my code instead of metrics.heightPixels ?
+ that I've set the height of LinearLayout 500dp, so I used 500 in my code...
my code is here :
LinearLayout mLL = (LinearLayout) findViewById(R.id.mLL);
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
mLL.setScaleY(metrics.heightPixels/(float)500);
mLL.addView(mGraphView);
THANK YOU :)
SOLVED ! ( I can't answer my question until next few hours because of low reputation, so I've edited my post... :) )
I had to define LinearLayout in XML file like this :
<LinearLayout
android:id="#+id/mLinearLayout"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_above="#+id/mlinearLayout2"
android:layout_below="#+id/title"
android:layout_centerHorizontal="true"
android:orientation="vertical" >
as you can see, I have used android:layout_height="100dp" and android:layout_above="#+id/mlinearLayout2" ( I have used another linear layout under mLinearLayout ) codes together and then Graph was viewable without any ForceClose in a FullScreen LinearLayout :)
I hope this post help others to solve their similar problems easily with some changes in codes !:)
I've found out this, too : If you want to get LinearLayout height anyway, you can use this code :
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus == true) {
LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.myLinearLayout);
int layoutWidth = myLinearLayout.getWidth();
int layoutHeight = myLinearLayout.getHeight();
}
}
getWindowManager().getDefaultDisplay().getMetrics(metrics);
I dont know if gives the same output as yours but worth a try.
Based on metrics.heightPixels i think you can adjust your view's dimensoins
I searched the internet for an easy way, but could not find one after hours of searching.
This is what I used, because there is no way (it seems) to get this value directly. I first get the dimensions of the Display. I obtain the height of the action and notifiaction bar and substract them:
int height = 0;
private void obtainHeight() {
int actionBarHeight = 0;
int notificationBarHeight = 0;
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
height = size.y;
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
}
int resourceIdStatusBar = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceIdStatusBar > 0) {
notificationBarHeight = getResources().getDimensionPixelSize(resourceIdStatusBar);
}
height = height - actionBarHeight - notificationBarHeight;
}
Navigation bar you can get with (not needed to be substracted, because its usually not part of the display):
Resources resources = this.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
naviigationBarHeight = resources.getDimensionPixelSize(resourceId);
}
Please get me correctly over here :
I want to get the height/width of the space available to the Activity/Layout in onCreate() method to calculate the height that can be given to child layouts. I can get the screen size using :
root = (LinearLayout) findViewById(R.id.mainroot); // Main layout of LinearLayout
android.view.Display display = getWindowManager().getDefaultDisplay();
int height = Display.getHeight(); // I know this is deprecated have hence used
int width = Display.getWidth(); // DisplayMetrics
int childWidth, childHeight;
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
//int density = metrics.densityDpi;
height = metrics.heightPixels; //480
width = metrics.widthPixels; //320
This both the methods/ways gives me same height and width i.e. size of full screen. What I am looking for is to get actual height that is avaialbe for the layout after deduction of Application Title, Status Bar, etc.
Any idea how to get this. OR to get the sizes of titles, etc - what all should be counted over here. On emulator I see 2 bars on top - 1 must be application titile what an be the other one. I can get heights of them all and deduct from screen height.
ONE more point : In this case I will be setting the height programamtically so it will be pixel based (as I can setheight in pixels only I guess) will that affect in density factor with differnet screen sizes. What can be a way to calculate height (lets say 50%) for child layout that will be same for any density o so.
SOLUTION :
In my onCreate(), I added the following lines :
setContentView(R.layout.mainpage);
root = (LinearLayout) findViewById(R.id.mainroot);
root.post(new Runnable() {
public void run() {
Rect rect = new Rect();
Window win = getWindow();
win.getDecorView().getWindowVisibleDisplayFrame(rect);
int statusHeight = rect.top;
int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
titleHeight = contentViewTop - statusHeight;
Log.i(Utility.TAG, "titleHeight = " + titleHeight + " statusHeight = " + statusHeight + " contentViewTop = " + contentViewTop);
// CALCULATE THE SIZE OF INNER LAYOUTS
calculateChildSize();
}
});
With the above code, I get the values of titleBar & statusBar. On deducting it from metrics.heightPixels; I get the required height of the screen.
Good Point is this code works for all density's.
Hope this helps others too.
FOR IMPROVEMENT : I have to do similar calculations for all Activities in my application, so was thinking about writing this code only once. I can save teh titleHeight to a static variable so can use in all activities.
BUT
Can the user change the phone's density at runtime.
If so, then the Activity's onCreate will be called again or not ?
If not, then can I trap the density change event where I can add this code and make the current activity to refresh.
Any idea suggestions for improving is appreciated.
//Where rootView is the object for the root view of your application
final int viewWidt = rootView.getMeasuredWidth();
There is very easy method for that. doOnLayout() method is called as soon as layout is measured and ready:
rootView.doOnLayout {
rootView.getMeasuredWidth()
rootView.getMeasuredHeight()
}
Is there a way to obtain the size of the notification bar and title bar in android? At the moment I obtain the display width and height with:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
After that I want to subtract the sizes of the bars so that I can stretch a video without losing aspect ratio. Currently I hide the bars because I can't see a better way.
Maybe this is a helpful approach: Referring to the Icon Design Guidelines there are only three different heights for the status (notification) bar depending on the screen density:
24px for LDPI
32px for MDPI
48px for HDPI
So if you retrieve the screen density of the device using densityDpi of DisplayMetrics you know which value to subtract
so it could look something like that:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int myHeight = 0;
switch (metrics.densityDpi) {
case DisplayMetrics.DENSITY_HIGH:
Log.i("display", "high");
myHeight = display.getHeight() - 48;
break;
case DisplayMetrics.DENSITY_MEDIUM:
Log.i("display", "medium/default");
myHeight = display.getHeight() - 32;
break;
case DisplayMetrics.DENSITY_LOW:
Log.i("display", "low");
myHeight = display.getHeight() - 24;
break;
default:
Log.i("display", "Unknown density");
*As for as I know, this works perfectly.
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}*
Martin's answer specified the wrong height (at least as of SDKv11). As per Icon Design Guidelines, the status bar icons have a height of 25dp, not 32dp. 25dp translates into these density-specific heights:
19px for LDPI
25px for MDPI
38px for HDPI
50px for XHDPI
An easy way to observe these sizes is to use the hierarchyviewer against an emulator or device with a normal density. Simply look at the value of getHeight() for the title bar's FrameLayout. The status bar is a bit trickier because it's part of the DecorView and not a view in itself, so get its height indirectly by looking at mTop for the title bar's FrameLayout, which is positioned immediately below the status bar. Per my observations the status bar and title bar each match the 25dp height of the status bar icons (I have not seen a declaration of this fact in the android ref as of SDKv11).
I use the following code for getting heights:
For Status (Notification) bar:
View decorView = getWindow().getDecorView();
Rect rect = new Rect();
decorView.getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
For Title bar:
View contentView = getWindow().findViewById(Window.ID_ANDROID_CONTENT);
int[] location = new int[2];
contentView.getLocationInWindow(location);
int titleBarHeight = location[1] - statusBarHeight;
hi i think that isn´t necessary and that will be automatically if you use a VideoView
VideoView vv = (VideoView) findViewById(R.id.MainVideo);
MediaController mc=new MediaController(this);
mc.setEnabled(true);
mc.show(0);
vv.setMediaController(mc);
vv.setVideoURI(Uri.parse(URLMedia));
vv.requestFocus();
vv.showContextMenu();
vv.start();
i have found a tutorial may be it would be helpful for u
helpful for me thou!
How to increase the size of the title bar in an Android application?
you can change your title bar size and the way you want it you can get it lucky chap !
have Fun
sorry for dummy comment, but that's no correct to use constants as height of notification bar.
just get the global view (PhoneWindow$DecorView) then get it's child (it'll be only one view (FrameLayout)). this layout contain You'r app views and measure whole screen (#see FrameLayout.mHeight). the first layout of it will be You'r first view, so getting the top of it will give You the right notification bar's height. Using FrameLayout without it's context will bring you nothing, cuz the top of you'r child will be equal to 0 in that case.
for lazy one's :
ViewGroup decoreView = (ViewGroup)*YourActivityViewHere*.getRootView();
int barSize = ((ViewGroup)decoreView.getChildAt(0)).getChildAt(0).getTop();
you can also use
getWindow().getDecorView().getRootView()
instead of YourActivityViewHere
This works waaaay better than hardcoding values because android will still return the value that would be the height of the status bar or action bar on that particular device even though they may not be visible.
So, the idea is to get the content view onto which all of your views are added.
public View getContentView(Activity a) {
int id = a.getResources().getIdentifier("content", "id", "android");
return a.findViewById(id);
}
Then, in your activity
View cView = getContentView(this);
cView.post(()->{
int offsetY = cView.getTop();
// do whatever here.
});
The good thing with the above code is that it'll also account for the action bar.