Android基礎之擷取LinearLayout的寬高_Android

來源:互聯網
上載者:User

前言

看到題目擷取LinearLayout寬高,或許大家想到的解決方案如下:

public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  LinearLayout ll = (LinearLayout) findViewById(R.id.layInfo); Log.i("w", ll.getWidth()+"L"+ll.getHeight());}

你會發現列印出來是0

那是因為在onCreate方法的時候LinearLayout還並沒有繪製完成,所以擷取的高度均為0,

或者試著把這段代碼放到onResume()方法中去,依然是0。

實現方法

如果我們用擷取LinearLayout的寬高

可以通過定時器不斷的監聽LinearLayout的寬高,等繪製完成後,關閉定時器即可。

final Handler handler= new Handler(){   @Override   public void handleMessage(Message msg) {   if(msg.what == 1) {    if(ll.getWidth()!=0) {    Log.i("w", ll.getWidth()+"L"+ll.getHeight());      timer.cancel();    }   }    }  };  timer = new Timer();  TimerTask task = new TimerTask(){   public void run() {     Message message = new Message();     message.what = 1;     myHandler.sendMessage(message);     }    };   timer.schedule(task,10,1000);  }

類似,如果想在Activity啟動後立即彈出PopupWindow,我們知道在Activity的onCreate()方法中直接寫彈出PopupWindow方法會報錯,因為activity沒有完全啟動是不能彈出PopupWindow

我們可以嘗試用兩種方法實現:

1、用onWindowFocusChanged方法

@Overridepublic void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); showPopupWindow();}

2、用HandlerRunnable,延時

@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mHandler.postDelayed(mRunnable, 1000);}private Runnable mRunnable = new Runnable() { public void run() { showPopupWindow(); }};

這樣擷取LinearLayout寬高問題就解決了。

總結

以上就是這篇文章的全部內容了,希望本文的內容對各位Android開發人員們能有所協助,如果有疑問大家可以留言交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.