1. 程式人生 > >在自定義view中獲取android layout_width等屬性值

在自定義view中獲取android layout_width等屬性值

這裡以獲取layout_width和layout_height為例

1,新建attr檔案

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="album">
        <attr name="android:layout_width"/>
        <attr name="android:layout_height"/>
    </declare-styleable>
</resources>

2,在view建構函式中獲取屬性值:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.album, defStyleAttr, 0);
try {
    int width = a.getLayoutDimension(R.styleable.album_android_layout_width, -1);
    int height = a.getLayoutDimension(R.styleable.album_android_layout_height, -2);
    Log.d(TAG, "AlbumView: " + width + " " + height);
} finally {
  a.recycle();
}