Android中的自訂視圖控制項

來源:互聯網
上載者:User

標籤: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中的自訂視圖控制項

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.