標籤:
在activity中可以調用View.getWidth、View.getHeight()、View.getMeasuredWidth() 、View.getgetMeasuredHeight()來獲得某個view的寬度或高度,但是在onCreate()、onStrart()、onResume()方法中會返回0,這是應為當前activity所代表的介面還沒顯示出來沒有添加到WindowPhone的DecorView上或要擷取的view沒有被添加到DecorView上或者該View的visibility屬性為gone 或者該view的width或height真的為0 ,所以只有上述條件都不成立時才能得到非0的width和height。
View的事件回調裡使用
這時候該view已經被顯示即被添加到DecorView上 如點擊事件 觸摸事件 焦時間點事件等
View view=findViewById(R.id.tv); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int width = v.getWidth(); } });onWindowFocusChanged() 回調
在activity被顯示出來時即添加到了DecorView上時擷取寬和高如onWindowFocusChanged() 回調方法
@Override public void onWindowFocusChanged(boolean hasFocus) { View iv1 = findViewById(R.id.iv1); View iv2=findViewById(R.id.iv2); String msg1="iv1‘ width:"+iv1.getWidth()+" height:"+iv1.getHeight()+" measuredWidth:"+iv1.getMeasuredWidth()+"measuredHeight:"+iv1.getMeasuredHeight(); String msg2="iv2‘ width:"+iv2.getWidth()+" height:"+iv2.getHeight()+" measuredWidth:"+iv2.getMeasuredWidth()+"measuredHeight:"+iv2.getMeasuredHeight(); Log.i("onWindowFocusChanged() "+msg1); Log.i("onWindowFocusChanged() "+msg2); super.onWindowFocusChanged(hasFocus); }延時
在onResume方法最後開線程300毫秒左右後擷取寬和高 因為onResume執行完後300毫秒後,介面就顯示出來了。
view.postDelayed(new Runnable() { @Override public void run() { View iv1 = findViewById(R.id.iv1); View iv2=findViewById(R.id.iv2); String msg1="iv1‘ width:"+iv1.getWidth()+" height:"+iv1.getHeight()+" measuredWidth:"+iv1.getMeasuredWidth()+"measuredHeight:"+iv1.getMeasuredHeight(); String msg2="iv2‘ width:"+iv2.getWidth()+" height:"+iv2.getHeight()+" measuredWidth:"+iv2.getMeasuredWidth()+"measuredHeight:"+iv2.getMeasuredHeight(); Log.i("onWindowFocusChanged() "+msg1); Log.i("onWindowFocusChanged() "+msg2); } }, 300);在onCreate()或onResume()等方法中需要
getViewTreeObserver().addOnGlobalLayoutListener()來添為view加回調在回調裡獲得寬度或者高度擷取完後讓view刪除該回調
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { view.postDelayed(new Runnable() { @Override public void run() { View iv1 = findViewById(R.id.iv1); View iv2=findViewById(R.id.iv2); String msg1="iv1‘ width:"+iv1.getWidth()+" height:"+iv1.getHeight()+" measuredWidth:"+iv1.getMeasuredWidth()+"measuredHeight:"+iv1.getMeasuredHeight(); String msg2="iv2‘ width:"+iv2.getWidth()+" height:"+iv2.getHeight()+" measuredWidth:"+iv2.getMeasuredWidth()+"measuredHeight:"+iv2.getMeasuredHeight(); Log.i("onWindowFocusChanged() "+msg1); Log.i("onWindowFocusChanged() "+msg2); } }, 300); } });我是天王蓋地虎的分割線
參考:http://blog.csdn.net/nailsoul/article/details/25909313
Android -- 擷取View寬高