我已使用Runnable
查找状态栏的高度,并提供正确的输出。
但如何在run()
的{{1}}方法之外访问 StatusBarHeight ?
这是我的代码:
Runnable
P.S。 :如果我在@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RelativeLayout main = (RelativeLayout) findViewById(R.id.main);
final Rect rectgle = new Rect();
final Window window = getWindow();
main.post(new Runnable() {
@Override
public void run() {
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
int StatusBarHeight = rectgle.top;
int contentViewTop = window.findViewById(
Window.ID_ANDROID_CONTENT).getTop();
int TitleBarHeight = contentViewTop - StatusBarHeight;
Log.i("ScreenDemo", "StatusBar Height= " + StatusBarHeight
+ " , TitleBar Height = " + TitleBarHeight);
}
});
}
中直接在run()
内编写代码,则会返回 0 ,因为UI尚未呈现。
任何帮助表示赞赏。
答案 0 :(得分:3)
你的变量StatusBarHeight
的范围是块内的本地,如果你想从onCreate()方法访问它,那么你需要按照以下方式声明它,
private static int StatusBarHeight; // class level declaration
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RelativeLayout main = (RelativeLayout) findViewById(R.id.main);
final Rect rectgle = new Rect();
final Window window = getWindow();
main.post(new Runnable() {
@Override
public void run() {
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
StatusBarHeight = rectgle.top;
int contentViewTop = window.findViewById(
Window.ID_ANDROID_CONTENT).getTop();
int TitleBarHeight = contentViewTop - StatusBarHeight;
Log.i("ScreenDemo", "StatusBar Height= " + StatusBarHeight
+ " , TitleBar Height = " + TitleBarHeight);
}
});
}
答案 1 :(得分:1)
您需要在类中将变量声明为私有成员变量,以便可以在Runnable
之外访问它。像这样:
private int statusBarHeight; // member variable available to all methods in the class
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RelativeLayout main = (RelativeLayout) findViewById(R.id.main);
final Rect rectgle = new Rect();
final Window window = getWindow();
main.post(new Runnable() {
@Override
public void run() {
window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
statusBarHeight = rectgle.top;
int contentViewTop = window.findViewById(
Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight = contentViewTop - statusBarHeight;
Log.i("ScreenDemo", "StatusBar Height= " + statusBarHeight
+ " , TitleBar Height = " + titleBarHeight);
}
});
}
注意:我已将变量名称从StatusBarHeight
更改为statusBarHeight
,从TitleBarHeight
更改为titleBarHeight
。请记住为变量使用初始小写名称。 Java命名约定使用初始小写变量名和类名的初始大写。