Android 自訂View1,android自訂view1

來源:互聯網
上載者:User

Android 自訂View1,android自訂view1

 目標是做一個牛叉的日曆,但是要先一步步來,先看

簡單一點說就是吧自訂view平分成七個部分,每個部分寫上一個字,然後自訂view可以跟隨手指滑動,並在抬起手指後恢複到初始位置,並且點擊view可以判斷出點的是哪個view(都是用座標算出來)

代碼也簡單,看一下就ok

public class AAAView extends View {    private Paint paint;    private float moveX;//移動距離    private float downX;//手指按下的位置    private int r;//每個字的半徑    private int d;//直徑    private int location;//手指按在哪個字上    private Context context;    public AAAView(Context context) {        super(context);        init(context);    }    public AAAView(Context context, @Nullable AttributeSet attrs) {        super(context, attrs);        init(context);    }    public AAAView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init(context);    }    private void init(Context context) {        paint = new Paint();        paint.setColor(Color.BLACK);        paint.setTextSize(25);        this.context = context;    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        r = getWidth() / 14;        d = 2 * r;        for (int i = 0; i < 7; i++) {            canvas.drawText("a", r + i * 2 * r + moveX, 30, paint);        }    }    @Override    public boolean onTouchEvent(MotionEvent event) {        switch (event.getAction()) {            case MotionEvent.ACTION_DOWN:                downX = event.getX();                location = (int) Math.ceil(downX / d);                return true;            case MotionEvent.ACTION_MOVE:                moveX = (int) (event.getX() - downX);                invalidate();                return true;            case MotionEvent.ACTION_UP://每次抬起手勢後,要恢複初始狀態                moveX = 0;                invalidate();                if (event.getX() < location * d && event.getX() > (location - 1) * d) {                    Toast.makeText(context, "點擊了第" + location + "個字", Toast.LENGTH_LONG).show();                }                return true;        }        return super.onTouchEvent(event);    }}

萬事開頭難,估計日曆系列要寫很久,不過慢慢來,應該可以搞定

聯繫我們

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