標籤:raw highlight state rri get 程式 select 視圖 nbsp
簡介
當現有控制項不能滿足需求時,就需要自訂控制項。
自訂控制項屬性
自訂控制項首先要繼承自View,重寫兩個建構函式。
第一個是代碼中使用的:
public MyRect(Context context) {super(context);}
另一個是資源解析程式使用的:
public MyRect(Context context, AttributeSet attrs) {super(context, attrs);TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyView);int color = ta.getColor(R.styleable.MyView_rect_color, 0xff00ffff);setBackgroundColor(color);ta.recycle();}
也可以給自訂控制項指定屬性,建立attrs.xml:
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="MyView"> <attr name="rect_color" format="color"/> </declare-styleable></resources>
然後就可以在layout檔案中使用了:
<com.wanxiang.www.learncustomview.MyRect android:id="@+id/myrect" android:layout_width="100dp" android:layout_height="100dp" jkxy:rect_color="#FF000FFF"/>
自訂控制項皮膚
可以給button等控制項通過background屬性設定背景,並根據控制項的狀態做出改變。定義background為一個xml:
<Button android:text="Button" android:background="@drawable/button_skin" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/button"/>
定義這個xml檔案內容為:
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="false" android:drawable="@drawable/btn_normal"></item> <item android:state_pressed="true" android:drawable="@drawable/btn_pressed"></item></selector>
即可以實現控制項背景根據狀態做出改變。
利用繪圖API自訂視圖
覆蓋draw函數:
@Overridepublic void draw(Canvas canvas) {super.draw(canvas);canvas.drawRect(0,0,500,500,paint);}
private void initproperties() {
paint = new Paint();
paint.setColor(Color.RED);
}
Android中的自訂視圖控制項