標籤:android 擷取view大小
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 是ViewTreeObserver的內部類,當一個視圖樹的布局發生改變時,可以被ViewTreeObserver監聽到,當介面顯示的時候,這個方法也會被調用,所以擷取view的大小可以放在這個方法裡面
引用自:http://bbs.csdn.net/topics/390672372
Android - 總結Activity與Fragment開啟的時候擷取組件的大小