安卓零碎知识集中(2)
1、获取标题栏的高度
Rect frame = new Rect(); getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT) .getTop(); int titleBarHeight = contentTop - statusBarHeight; textView.setText("statusBarHeight" + statusBarHeight + ";contentTop=" + contentTop + ";titleBarHeight" + titleBarHeight);
2、以Acivity作为布局
注:该类必须继承ActivityGroup
LocalActivityManager activityManager; activityManager = getLocalActivityManager(); View view2 = activityManager.startActivity("act2",new Intent(this, Act2.class)).getDecorView(); linearLayout.addView(view2, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
3、屏幕截图并保存
View view = getWindow().getDecorView(); Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Config.RGB_565); view.draw(new Canvas(bitmap)); imageView.setImageBitmap(bitmap);
4、android 获取组件尺寸大小
在oncreate()中利用view.getWidth()或是view.getHeiht()来获取view的宽和高,看似没有问题,其实他们去得值是0,并不是你想要的结果?
这是为什么呢?
在调用oncreate()方法时,界面处于不可见状态,内存加载组件还没有绘制出来,你是无法获取他的尺寸。
那如何在绘制组件之前能获取到该组件的尺寸大小呢?
这里有三种方法,经过验证的:
(1)
int width =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); int height =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); view.measure(width,height); int height=view.getMeasuredHeight(); int width=view.getMeasuredWidth();
(2)
//增加组件绘制之前的监听 ViewTreeObserver vto =view.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public booleanonPreDraw() { int height =view.getMeasuredHeight(); int width =view.getMeasuredWidth(); } });(3)
//增加整体布局监听 ViewTreeObserver vto = view.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){ @Override public voidonGlobalLayout() { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); int height =view.getMeasuredHeight(); int width =view.getMeasuredWidth(); } });那么,在activity进入运行期时,组件的尺寸获取方法就很简单了,直接getWidth()和getHeight().
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。