Android自定义view自定义属性怎么使用,请牛人指导

2025-04-04 19:55:03
推荐回答(1个)
回答1:

首先定义一下自定义属性,一种好的习惯是自定义的属性集合的名字要和使用这些属性的自定义View的类名一致,当然, 这个也不是必须的, 比如如下的属性集合, 也可以用在OtherCustomeView里。


   
   


布局文件中定义DrawableTextView的时候, 就可以使用定义好的自定义属性了,如app:开头的属性。

    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/model_my_customer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/defaultBlueButtonColor"
    android:textSize="22sp"
    android:text="@string/model_my_customer"
    android:gravity="center_vertical"
    android:drawableLeft="@drawable/model_my_customer_icon"
    android:drawablePadding="10dip"
    app:drawableHeight="45dip"
    app:drawableWidth="45dip" />


在DrawableTextView.java类里读出属性值

public DrawableTextView(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DrawableTextView);
    //图片的高度
    mDrawableHeight = typedArray.getDimensionPixelSize(R.styleable.DrawableTextView_drawableHeight, 0);
    mDrawableWidth = typedArray.getDimensionPixelSize(R.styleable.DrawableTextView_drawableWidth, 0);
    typedArray.recycle();
}