源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android基础之获取LinearLayout的宽高

  • 时间:2020-02-18 01:04 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android基础之获取LinearLayout的宽高
[b]前言[/b] 看到题目获取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, 或者试着把这段代码放到[code]onResume()[/code]方法中去,依然是0。 [b]实现方法[/b] [b]如果我们用获取LinearLayout的宽高 [/b] 可以通过定时器不断的监听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的[code]onCreate()[/code]方法中直接写弹出[code]PopupWindow[/code]方法会报错,因为activity没有完全启动是不能弹出[code]PopupWindow[/code]。 [b]我们可以尝试用两种方法实现:[/b] 1、用[code]onWindowFocusChanged[/code]方法
@Override
public void onWindowFocusChanged(boolean hasFocus) {
 super.onWindowFocusChanged(hasFocus);
 showPopupWindow();
}
2、用[code]Handler[/code]和[code]Runnable[/code],延时
@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宽高问题就解决了。 [b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对各位Android开发者们能有所帮助,如果有疑问大家可以留言交流。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部