美文网首页技术分享
Android获取LinearLayout宽高

Android获取LinearLayout宽高

作者: 洪生鹏 | 来源:发表于2016-06-13 21:30 被阅读0次

有的时候,我们需要想获取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());
}

你会发现打印出来是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方法
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    showPopupWindow();
}
  1. 用Handler和Runnable,延时
@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宽高问题就解决了。

相关文章

网友评论

    本文标题:Android获取LinearLayout宽高

    本文链接:https://www.haomeiwen.com/subject/zknydttx.html