AndroidカスタムグレーのButtonを押す

1994 ワード

実現は比較的簡単である. 
public class UIButton extends Button
{
    
    private int COVER_ALPHA = 48;
    private Paint mPressedPaint;
    private int mPressedColor;
    private int WIDTH;
    private int HEIGHT;
    private int mRadius;
    
    public UIButton(Context context) {
        super(context);
        init(context);
    }
    
    protected void init(Context context) {
        //mRadius = 10; ,  Button 
        mRadius = 0;
        mPressedColor = Color.GRAY;
        mPressedPaint = new Paint();
        mPressedPaint.setStyle(Paint.Style.FILL);
        mPressedPaint.setColor(mPressedColor);
        mPressedPaint.setAlpha(0);
        mPressedPaint.setAntiAlias(true);
    }
    
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        WIDTH = w;
        HEIGHT = h;
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        RectF rectF = new RectF();
        rectF.set(0, 0, WIDTH, HEIGHT);
        canvas.drawRoundRect(rectF, mRadius, mRadius, mPressedPaint);
        
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPressedPaint.setAlpha(COVER_ALPHA);
                invalidate();
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                mPressedPaint.setAlpha(0);
                invalidate();
                break;
        }
        return super.onTouchEvent(event);
    }
    
}

リファレンスhttps://github.com/drakeet/AndroidUIView
これは良い標準的なカスタムコントロールの例です.
学習の注意点:
  Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);         paint.setColor(Color.BLUE);         canvas.drawLine(0, 0, 100, 1000, paint);         canvas.drawText("test", 0,200, paint);//注意textの描画は下から上へ!tの下から!!0,0と書けば見えない!!        view.draw(canvas);