標籤:android style blog class code java
1.attr.xml
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="MyView"> <attr name="textColor" format="color" /> <attr name="textSize" format="dimension" /> </declare-styleable></resources>
2.在構造方法中使用
public MyView(Context context,AttributeSet attrs){ super(context,attrs); mPaint = new Paint(); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView); int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF); //怎麼擷取:名字_ 屬性 串連起來就可以 float textSize = a.getDimension(R.styleable.MyView_textSize, 36); mPaint.setTextSize(textSize); mPaint.setColor(textColor); a.recycle(); }
3.在布局檔案中使用
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:test="http://schemas.android.com/apk/res/com.android.tutor" //自訂屬性首碼 與 包名 android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><com.android.tutor.MyView android:layout_width="fill_parent" android:layout_height="fill_parent" test:textSize="20px" test:textColor="#fff"/></LinearLayout>