代码:
@Override public void onWindowFocusChanged(boolean hasFocus) { // TODO Auto-generated method stub super.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
代码:
Button button1; private int width ; private Handler mHandler; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.activity_one, null); mHandler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); if(msg.what == 200){ width = msg.arg1; Log.i("TAG", "button1-->"+button1); Log.i("TAG", "width-->"+width); } } }; return mView; } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); initWidget(); ViewTreeObserver vto = button1.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { width = button1.getWidth(); Message msg = new Message(); msg.what = 200; msg.arg1 = width; mHandler.sendMessage(msg); } }); }
引用自:http://bbs.csdn.net/topics/390672372
Android - 总结Activity与Fragment打开的时候获取组件的大小
原文地址:http://blog.csdn.net/u013372185/article/details/44982147