Android獲取LinearLayout寬高
有的時(shí)候,我們需要想獲取LinearLayout寬高
1.獲取LinearLayout寬高
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- LinearLayout ll = (LinearLayout) findViewById(R.id.layInfo);
- Log.i("w", ll.getWidth()+"L"+ll.getHeight());
- }
你會(huì)發(fā)現(xiàn)打印出來是0
那是因?yàn)樵趏nCreate方法的時(shí)候LinearLayout還并沒有繪制完成,所以獲取的高度均為0,
或者試著把這段代碼放到onResume()方法中去,依然是0。
如果我們用獲取LinearLayout的寬高
可以通過定時(shí)器不斷的監(jiān)聽LinearLayout的寬高,等繪制完成后,關(guān)閉定時(shí)器即可。
- 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啟動(dòng)后立即彈出PopupWindow,我們知道,
在Activity的onCreate()方法中直接寫彈出PopupWindow方法會(huì)報(bào)錯(cuò),因?yàn)閍ctivity沒有完全啟動(dòng)是不能彈出PopupWindow。
我們可以嘗試用兩種方法實(shí)現(xiàn):
2.用onWindowFocusChanged方法
- @Override
- public void onWindowFocusChanged(boolean hasFocus) {
- super.onWindowFocusChanged(hasFocus);
- showPopupWindow();
- }
3.用Handler和Runnable,延時(shí)
- @Override
- protected 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寬高問題就解決了。
【本文為51CTO專欄作者“洪生鵬”的原創(chuàng)稿件,轉(zhuǎn)載請(qǐng)聯(lián)系原作者】