Android 獲取控制元件的寬高 dp和px之間的轉換
阿新 • • 發佈:2019-02-09
怎麼獲取控制元件的高度呢 先看一下xml的佈局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="horizontal" > <ImageView android:id="@+id/imageView1" android:layout_width="200dp" android:layout_height="400dp" android:src="@drawable/tmp_image4" /> </LinearLayout>
先看程式碼部分
我如果直接列印 那麼列印的結果為0 0 並不是 在xml中設定的w 200dp h400dppublic class MainActivity extends Activity { private ImageView imageView; private String TAG="debug"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView=(ImageView)findViewById(R.id.imageView1); Log.d(TAG, "---->"+imageView.getHeight()+" "+imageView.getWidth()); } }
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Log.d(TAG, "---->"+imageView.getHeight()+" "+imageView.getWidth());
}
});
為什麼是600 300 因為xml單位是dp 程式碼中是px 因此會差一點 但是每次獲取控制元件的寬高都需要onclik 有點費事
ViewTreeObserver viewTreeObserver = imageView.getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @Override public void onGlobalLayout() { imageView.getViewTreeObserver().removeGlobalOnLayoutListener( this); Log.d(TAG, "---->" + imageView.getHeight() + " "+ imageView.getWidth()); } });
還是600 300 並且不需要點選事件就可以直接列印 再來說一下 px和dp的轉換
ViewTreeObserver viewTreeObserver = imageView.getViewTreeObserver();
viewTreeObserver
.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
imageView.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
Log.d(TAG, "---->" + px2dip(MainActivity.this, imageView.getHeight()) + " "
+ px2dip(MainActivity.this, imageView.getWidth()));
}
});
}
//dp->px
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
//px->dp
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
08-01 18:19:47.016: D/debug(8928): ---->400 200
搞定 當時找到的時候忘記記下出處 現在翻出來沒有標註 見諒……