2016-06-29 9 views
2

私はカスタムビューを作成しています。レイアウトファイルでは、幅を200dp、高さを200dpに設定しました。私は、ビューの幅を取得するためにgetWidth()getMeasuredWidth()を使用していカスタムビューの測定

<com.example.baoshuai.mydefineview.MyTextView 
    android:layout_width="300dp" 
    android:layout_height="300dp" 
    android:layout_margin="30dp" 
    android:text="Hello,Sunshine" 
    android:textAllCaps="false" 
    android:paddingTop="40dp" 
    android:textAlignment="center"/> 

は、値が200dpが、700dpではありません。私は測定結果を得るのはここです:ここでは

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    canvas.drawColor(Color.BLUE); 
    int width = getWidth(); 
    int height = getHeight(); 
    Log.d("get","Width:"+width+" Height:"+height); 
    int measuredWidth = getMeasuredWidth(); 
    int measuredHeight = getMeasuredHeight(); 
    Log.d("getMeasured","measuredWidth:"+measuredWidth+" measuredHeight:"+measuredHeight); 
} 

はスクリーンショットです:あなたが定義されている

enter image description here

答えて

0
android:layout_width="300dp" 
    android:layout_height="300dp" 

値はdpです。プログラムで幅と高さを取得する場合、int width = getWidth();の値はピクセル単位です。

これは異なる値に見えますが、同じです。

レイアウトでpxの値を適用し、プログラムで表示することで同じことを確認できます。

Refere https://stackoverflow.com/a/2025541/3817374 Androidのさまざまなユニットについて詳しくは、こちらをご覧ください。

+0

ありがとう、私は間違いを見つけました。 – lbs0912