Android - 總結Activity與Fragment開啟的時候擷取組件的大小

來源:互聯網
上載者:User

標籤: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開啟的時候擷取組件的大小

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.