상태 표시 줄의 높이?
상태 표시 줄 + 제목 표시 줄의 높이를 얻는 방법이 있습니까? 개발자 포럼을 확인하면 동일한 질문이 표시되지만 해결책은 없습니다 (찾을 수 있음).
초기 레이아웃 단계 후에 얻을 수 있다는 것을 알고 있지만 내 활동의 onCreate ()에서 가져올 수 있습니다.
감사
Rect rectgle= new Rect();
Window window= getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int StatusBarHeight= rectgle.top;
int contentViewTop=
window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int TitleBarHeight= contentViewTop - StatusBarHeight;
Log.i("*** Jorgesys :: ", "StatusBar Height= " + StatusBarHeight + " , TitleBar Height = " + TitleBarHeight);
onCreate()
활동 의 메소드 에서 상태 표시 줄의 높이를 가져 오려면 다음 메소드를 사용하십시오.
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
이것은 오래된 질문이지만 대답이 작동하지 않는다는 것을 알았습니다 onCreate()
.
방법 에서 작동하는 이 코드를 여기 에서 찾았습니다.onCreate()
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
이 문제가 발생하는 모든 사람에게 도움이되기를 바랍니다.
저와 같이 XML 레이아웃에서 사용하려는 사람들을 위해 :
<...
android:layout_marginTop="@*android:dimen/status_bar_height"
... />
Android Studio (2.2 Preview 3-현재 작성 중)가이 개념을 지원하지 않는다는 사실을 혼동하지 마십시오. 런타임이 그렇습니다. Google의 소스 코드에서 가져 왔습니다.
상태 표시 줄 높이를 가져 오는 지원되는 방법은 WindowInsets
API 21 이상부터 시작 하는 클래스 를 사용하는 것입니다 .
customView.setOnApplyWindowInsetsListener((view, insets) -> {
// Handle insets
return insets.consumeSystemWindowInsets();
});
또는 WindowInsetsCompat
지원 라이브러리의 경우 :
ViewCompat.setOnApplyWindowInsetsListener(customView, (view, insets) -> {
// Handle insets
return insets.consumeSystemWindowInsets();
});
onApplyWindowInsets
뷰 내에서 메서드를 재정의 할 수도 있습니다 .
public class CustomView extends View {
@Override
public WindowInsets onApplyWindowInsets(final WindowInsets insets) {
final int statusBarHeight = insets.getStableInsetTop();
return insets.consumeStableInsets();
}
}
더 자세한 내용은 Chris Banes의 이야기- 윈도우 피팅 전문가 되기 ( 여기에서 슬라이드를 볼 수 있음 )를 확인하는 것이 좋습니다 .
다음 코드를 제안합니다.
Rect rect = new Rect();
Window window = activity.getWindow();
if (window != null) {
window.getDecorView().getWindowVisibleDisplayFrame(rect);
android.view.View v = window.findViewById(Window.ID_ANDROID_CONTENT);
android.view.Display display = ((android.view.WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
//return result title bar height
return display.getHeight() - v.getBottom() + rect.top;
}
두 가지 예 :
1) 기기 1 브랜드 : samsung, 기기 : maguro, 보드 : 참치, cpu_abi : armeabi-v7a, 디스플레이 : ICL53F.M420KREL08, 제조업체 : samsung, 모델 : Galaxy Nexus, 버전 : 4.0.2, 버전 : SDK : 14 ;
화면 해상도 : 1280 x 720.이 장치에는 하드웨어 버튼이 없습니다.
결과 :
rect: left=0 right=720 top=72 bottom=1208;
v: left=0 right=720 top=72 bottom=1208;
display: height=1208 width=720;
correct result=72;
장치 1에는 화면 상단에 제목 표시 줄이 있고 화면 하단에 소프트웨어 버튼이있는 상태 표시 줄이 있습니다.
2) 장치 2 장치 : bravo, 보드 : bravo, cpu_abi : armeabi-v7a, 디스플레이 : FRG83G, 제조업체 : HTC, 모델 : HTC Desire, 버전 릴리스 : 2.2.2, 버전 SDK : 8,
화면 해상도 : 800 x 400.이 장치에는 하드웨어 버튼이 있습니다.
결과 :
rect: left=0 right=480 top=38 bottom=800;
v: left=0 right=480 top=0 bottom=800;
display: height=800 width=480;
correct result: phone_bar_height=38;
장치 2에는 화면 상단에 제목 표시 줄이 있고 상태 표시 줄이 전혀 없습니다.
위에 두 가지 솔루션이 제안되었습니다.
A) v.getTop() - rect.top
( 장치 1의 경우 올바르지 않습니다. 72 대신 0을 제공합니다.)
B) display.getHeight() - v.getHeight()
( 장치 2의 경우 올바르지 않습니다. 38 대신 0을 제공합니다.)
다른:
display.getHeight() - v.getBottom() + rect.top
두 경우 모두 올바른 결과를 제공합니다.
최신 정보
3) 추가 예 (세 번째 장치) : 브랜드 : LGE, 장치 : v909, cpu_abi : armeabi-v7a, 디스플레이 : HMJ37, 모델 : LG-V909, 버전 릴리스 : 3.1, 버전 SDK : 12
rect: left=0 right=1280 top=0 bottom=720
v: left=0 right=1280 top=0 bottom=720
Display: height=768 width=1280
phone_bar_height=48
기기 3은 가로 방향이며 화면 상단에 제목 표시 줄이없고 화면 하단에 상태 표시 줄이 있습니다.
그래서 여기 :
int size_of_title_bar = rect.top;
int size_of_status_bar = display.getHeight() - v.getBottom();
장치 2와 3에 맞습니다. 장치 1에 대해 잘 모르겠습니다. 사용자가 장치 1의 스크린 샷을 보냈습니다. 거기에 소프트웨어 버튼이있는 상태 표시 줄이 있습니다. 그러나 "display.getHeight ()-v.getBottom ()"표현식은 0을 제공합니다.
이 블로그 게시물에서 설명 하는 방식을 사용하여 android의 dimens.xml 파일에있는 상태 표시 줄의 차원을 가져올 수도 있습니다 .
그리기를 기다릴 필요없이 상태 표시 줄의 높이를 가져올 수 있습니다.
블로그 게시물에서 코드 인용 :
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
이 메서드를 ContextWrapper 클래스에 넣어야합니다.
Attach a runnable to one of your views in your onCreate method, and place the above code in there. This will cause the application to calculate the status bar + titlescreen height when they are attached to the screen.
Take a look at the code below:
myView.post(new Runnable() {
@Override
public void run() {
Rect rectgle= new Rect();
Window window= getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int StatusBarHeight= rectgle.top;
int contentViewTop= window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int TitleBarHeight= contentViewTop - StatusBarHeight;
}
});
If this still doesn't do the trick, try invoking the view's postDelayed method instead of post and adding a millisecond value as the second argument.
I think better way to calculate that is to get height of fullscreen minus our main layout
phoneBarsHeight = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight()
- mainView.getHeight();
And you can put it in onGlobalLayout()
. This works on tablets too, I tried it on Theme.NoTitleBar, but it must always works.
Maybe you can even enhance it and use it onCreate()
by changing mainView.getHeight()
to mainView.getMeasuredHeight()
.
The solution posted by Jorgesys is very good, but it doesn't work inside onCreate() method. I guess it's because statusbar and titlebar are created after onCreate().
The solution is easy - you should put code inside runnable and execute it after onCreate() by using root.post((Runnable action) );
So the whole solution:
root = (ViewGroup)findViewById(R.id.root);
root.post(new Runnable() {
public void run(){
Rect rectgle= new Rect();
Window window= getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int StatusBarHeight= rectgle.top;
int contentViewTop=
window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int TitleBarHeight= contentViewTop - StatusBarHeight;
Log.i("*** jakkubu :: ", "StatusBar Height= " + StatusBarHeight +
" , TitleBar Height = " + TitleBarHeight);
}
});
I find it here
As of API 23 there is a better solution to getting the status bar height. API 23 adds a WindowInsets
feature, so you can use this code to get the size of the system insets, in this case at the top.
public int getStatusBarHeight() {
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
return binding.mainContent.getRootWindowInsets().getStableInsetTop();
}
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if(resourceId != 0) {
return getResources().getDimensionPixelSize(resourceId);
}
return 0;
}
Note that getRootWindowInsets()
will return null until after the View has been attached to a Window so it can't be used directly in onCreate()
but you can add a listener for the window attach and do it there - here I am adding the status bar inset to the size of my toolbar, which I hide and show, along with the status bar. When it's shown, I want the status bar over the top of it so I add the status bar height to the toolbar's top padding.
binding.mainContent.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View view) {
binding.toolbar.setPadding(binding.toolbar.getPaddingLeft(),
binding.toolbar.getPaddingTop() + getStatusBarHeight(),
binding.toolbar.getPaddingRight(), binding.toolbar.getPaddingBottom());
binding.mainContent.removeOnAttachStateChangeListener(this);
}
@Override
public void onViewDetachedFromWindow(View view) {
}
});
This may seem unrelated but most of the times, the reason that people look for the status bar height is to offset their own views so they are not placed under it.
By setting fitsSystemWindows
on the view you want to "push down" to give space to the status bar, it will be done automatically and according to the size of the status bar on each device. Padding will be added to the view that has this property set to true
.
Keep in mind that padding will only be added to the first view in the hierarchy with fitSystemWindows
set to true
This applies to cases where the status bar is translucent for example. Make sure that you set a Theme to the activity that doesn't have fitSystemWindows
set, otherwise the padding will be added to the activity instead (because it's first in the hierarchy).
This article is a good read on the subject
참고URL : https://stackoverflow.com/questions/3355367/height-of-statusbar
'developer tip' 카테고리의 다른 글
JavaScript : 정의되지 않음! == 정의되지 않음? (0) | 2020.11.16 |
---|---|
Android Eclipse 플러그인 : Instrumentation Test Runner가 지정되지 않음 (0) | 2020.11.16 |
Android 서비스는 항상 실행되어야 함 (일시 중지 또는 중지하지 않음) (0) | 2020.11.15 |
iPhone 인앱 구매 스크린 샷 (0) | 2020.11.15 |
정적 메서드 모의 (0) | 2020.11.15 |