直接看代码注释吧
package com.test01; import android.app.Activity; import android.graphics.Rect; import android.os.Bundle; import android.view.ViewTreeObserver; import android.view.Window; import android.widget.TextView; public class Test01Activity extends Activity { /** * 必须要设置一个View作为参照物 */ private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView) findViewById(R.id.tv); // 必须用这种方法获得。不用得到的数据为0 tv.post(new Runnable() { public void run() { init(); } }); // 获取控件的高度 ViewTreeObserver vto = tv.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { int height = tv.getMeasuredHeight(); int width = tv.getMeasuredWidth(); System.out.println(height+",,"+width); return true; } }); } private void init(){ Rect rect = new Rect(); Window window = getWindow(); tv.getWindowVisibleDisplayFrame(rect); // 状态栏的高度 int statusBarHeight = rect.top; // 标题栏跟状态栏的总体高度 int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop(); // 标题栏的高度:用上面的值减去状态栏的高度及为标题栏高度 int titleBarHeight = contentViewTop - statusBarHeight; System.out.println(statusBarHeight+"..."+contentViewTop+"..."+titleBarHeight); } }Android获得标题栏和状态栏高度,以及立即获取控件的高度
最新推荐文章于 2024-09-22 06:58:35 发布