【Android】获取控件的宽和高
生活随笔
收集整理的這篇文章主要介紹了
【Android】获取控件的宽和高
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
??????有時候我們須要在Activity的時候獲取控件的寬和高來做一些操作,以下介紹三種獲取寬和高的方式:
1. onWindowFocusChanged
@Overridepublic void onWindowFocusChanged(boolean hasFocus){super.onWindowFocusChanged(hasFocus);if (hasFocus){int width = image.getMeasuredWidth();int height = image.getMeasuredHeight();Toast.makeText(MainActivity.this, "width = " + width + "---height = " + height, Toast.LENGTH_SHORT).show();}}2. post方式
@Overrideprotected void onStart(){super.onStart();image.post(new Runnable(){@Overridepublic void run(){int width = image.getMeasuredWidth();int height = image.getMeasuredHeight();Toast.makeText(MainActivity.this, "onstart--width = " + width + "---height = " + height, Toast.LENGTH_SHORT).show();}});}3. ViewTreeObserver
ViewTreeObserver observer = image.getViewTreeObserver();observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){@Overridepublic void onGlobalLayout(){image.getViewTreeObserver().removeGlobalOnLayoutListener(this);int width = image.getMeasuredWidth();int height = image.getMeasuredHeight();Toast.makeText(MainActivity.this, "onglobal--width = " + width + "---height = " + height, Toast.LENGTH_SHORT).show();}});備注:以上image是ImageView控件
ImageView image = (ImageView)findViewById(R.id.image);
總結
以上是生活随笔為你收集整理的【Android】获取控件的宽和高的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 块状元素的text-align对齐属性
- 下一篇: Android-通过SlidingMen