本文主要是介绍Android - 总结Activity与Fragment打开的时候获取组件的大小,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Activity中获取 组件大小
代码:
@Overridepublic void onWindowFocusChanged(boolean hasFocus) {// TODO Auto-generated method stubsuper.onWindowFocusChanged(hasFocus);Log.d("TAG", "A-button1-->"+button1);Log.d("TAG", "A-width-->"+button1.getWidth());}
方法:在Activity中重写 onWindowFocusChanged()方法,然后直接在方法里面获取view的大小
解释:重写view中的onMeasure()方法可以知道,这个方法是用来计算view的宽度和高度,所以只要重写onMeasure()以 后的方法,然后再那个方法里面获取view的大小就行了。通过测试,一个Activity中,各种方法调用顺序如下:
其调用顺序为Activity.oncreate()→Activity.onResume()→
→TestImageView.onMeasure()→TestImageView.onLayout()→onGlobalLayoutListener()→
→Activity.onWidnowFocusChanged()→.....→
→TextImageView.onDraw()
引用自:http://www.xuebuyuan.com/1587193.html
fragment 中获取组件大小
代码:
Button button1;private int width ; private Handler mHandler;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {mView = inflater.inflate(R.layout.activity_one, null);mHandler = new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);if(msg.what == 200){width = msg.arg1;Log.i("TAG", "button1-->"+button1);Log.i("TAG", "width-->"+width);}}};return mView;}@Overridepublic void onResume() {// TODO Auto-generated method stubsuper.onResume();initWidget();ViewTreeObserver vto = button1.getViewTreeObserver();vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {@Overridepublic void onGlobalLayout() {width = button1.getWidth();Message msg = new Message();msg.what = 200;msg.arg1 = width;mHandler.sendMessage(msg);}});}
解释:因为在Fragment中没有 onWidnowFocusChanged ()这样的方法来重写,所以我们只能找别的方式,根据上面的方法调用顺序,可以看到vto.addOnGlobalLayoutListener()这个也在onMeasure()之后,OnGlobalLayoutListener 是
引用自:http://bbs.csdn.net/topics/390672372
这篇关于Android - 总结Activity与Fragment打开的时候获取组件的大小的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!