簡單的自訂View的實現

來源:互聯網
上載者:User

 項目中要用到一個記錄訂單數量的控制項,要求實現的效果是每次點擊這個控制項,裡面的值就會自動加一,直至加大最大之後又重新從一開始加。之前一直是使用預設的TextView來實現的,但是考慮到項目中又多個地方要用到這個控制項,所以決定把它自訂一下。

    
                 (控制項的)

    1、以前的實現的方法

int count = Integer.parseInt(amount.getText().toString());amount.setText(String.valueOf(count % 5 + 1));
   

   2、自訂View的方法

   首先定義一個View,叫AmountView,繼承自TextView。具體代碼如下:

import android.content.Context;import android.util.AttributeSet;import android.view.MotionEvent;import android.widget.TextView;/** * 自訂UI控制項,記錄菜的份數 *  * @school University of South China * @date 2014.01 */public class AmountView extends TextView {/** * 最大的份數 */private int mMaxAmount = 5;/** * 當前顯示的份數 */private int mAmount = 1;public AmountView(Context context) {super(context);setText(mAmount + "");}public AmountView(Context context, AttributeSet attrs) {super(context, attrs);setText(mAmount + "");}public AmountView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);setText(mAmount + "");}@Overridepublic boolean onTouchEvent(MotionEvent event) {if (event.getAction() == MotionEvent.ACTION_UP) {mAmount = mAmount % mMaxAmount + 1;setText(mAmount + "");System.out.println("AmoutView onTouchEvent");}return super.onTouchEvent(event);}public void setMaxAmount(int maxAmount) {mMaxAmount = maxAmount;}public void setAmount(int amount) {this.mAmount = amount;setText("" + mAmount);}}

注意的幾個地方:

(1)必須要實現預設的三個構造方法。

(2)setText方法的參數是Charsequece,不能傳int型參數,所以mAmount 後面加雙引號。

(3)在onTouchEvent()方法中處理點擊事件


然後在在布局檔案中用完整的包名申明該控制項即可使用了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.