Activity中获取 组件大小
代码:
@Override public void onWindowFocusChanged(boolean hasFocus) { // TODO Auto-generated method stub super.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; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.activity_one, null); mHandler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); if(msg.what == 200){ width = msg.arg1; Log.i("TAG", "button1-->"+button1); Log.i("TAG", "width-->"+width); } } }; return mView; } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); initWidget(); ViewTreeObserver vto = button1.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public 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