1.获取屏幕宽高
方法1:
int screenWIDth = getwindowManager().getDefaultdisplay().getWIDth(); // 屏幕宽(像素,如:480px) int screenHeight = getwindowManager().getDefaultdisplay().getHeight(); // 屏幕高(像素,如:800p) Log.e(TAG + " getDefaultdisplay","screenWIDth=" + screenWIDth + "; screenHeight=" + screenHeight);
方法2:
displayMetrics dm = new displayMetrics(); dm = getResources().getdisplayMetrics(); float density = dm.density; // 屏幕密度(像素比例:0.75/1.0/1.5/2.0) int densityDPI = dm.densityDpi; // 屏幕密度(每寸像素:120/160/240/320) float xdpi = dm.xdpi; float ydpi = dm.ydpi; Log.e(TAG + " displayMetrics","xdpi=" + xdpi + "; ydpi=" + ydpi); Log.e(TAG + " displayMetrics","density=" + density + "; densityDPI=" + densityDPI); screenWIDth = dm.wIDthPixels; // 屏幕宽(像素,如:480px) screenHeight = dm.heightPixels; // 屏幕高(像素,如:800px) Log.e(TAG + " displayMetrics(111)","screenWIDth=" + screenWIDth + "; screenHeight=" + screenHeight);
方法3:
dm = new displayMetrics(); getwindowManager().getDefaultdisplay().getMetrics(dm); density = dm.density; // 屏幕密度(像素比例:0.75/1.0/1.5/2.0) densityDPI = dm.densityDpi; // 屏幕密度(每寸像素:120/160/240/320) xdpi = dm.xdpi; ydpi = dm.ydpi; Log.e(TAG + " displayMetrics","density=" + density + "; densityDPI=" + densityDPI); int screenWIDthDip = dm.wIDthPixels; // 屏幕宽(dip,如:320dip) int screenHeightDip = dm.heightPixels; // 屏幕宽(dip,如:533dip) Log.e(TAG + " displayMetrics(222)","screenWIDthDip=" + screenWIDthDip + "; screenHeightDip=" + screenHeightDip); screenWIDth = (int)(dm.wIDthPixels * density + 0.5f); // 屏幕宽(px,如:480px) screenHeight = (int)(dm.heightPixels * density + 0.5f); // 屏幕高(px,如:800px) Log.e(TAG + " displayMetrics(222)","screenWIDth=" + screenWIDth + "; screenHeight=" + screenHeight);
2.获取控件的宽高,一般来说,我们在onCreate里面得到的控件的宽高全是0.采用下面的方法,可以得到真实的宽高
方法一 :
int w = VIEw.MeasureSpec.makeMeasureSpec(0,VIEw.MeasureSpec.UnspecIFIED); int h = VIEw.MeasureSpec.makeMeasureSpec(0,VIEw.MeasureSpec.UnspecIFIED); imageVIEw.measure(w,h); int height =imageVIEw.getMeasuredHeight(); int wIDth =imageVIEw.getMeasureDWIDth(); textVIEw.append("\n"+height+","+wIDth);
此方法会加载onMeasure三次
方法二 :
VIEwTreeObserver vto = imageVIEw.getVIEwTreeObserver(); vto.addOnPreDrawListener(new VIEwTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { int height = imageVIEw.getMeasuredHeight(); int wIDth = imageVIEw.getMeasureDWIDth(); textVIEw.append("\n"+height+","+wIDth); return true; } });
此方法会加载onMeasure二次,但是回调函数会回调很多次
方法三:
VIEwTreeObserver vto2 = imageVIEw.getVIEwTreeObserver(); vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @OverrIDe public voID onGlobalLayout() { imageVIEw.getVIEwTreeObserver().removeGlobalOnLayoutListener(this); textVIEw.append("\n\n"+imageVIEw.getHeight()+","+imageVIEw.getWIDth()); } });
此方法会加载onMeasure二次,但是回调函数只回调一次
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持编程小技巧!
总结以上是内存溢出为你收集整理的android获取屏幕宽高与获取控件宽高(三种方法)全部内容,希望文章能够帮你解决android获取屏幕宽高与获取控件宽高(三种方法)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)