一、自绘控件

 就是自己绘制的控件,通过onDraw()方法将控件绘制出来  自定义一个可点击的View  这个View可以记住用户点击的次数

 

public class CounterView extends View implements OnClickListener {

    private Paint mPaint;
    
    private Rect mBounds;

    private int mCount;
    
    public CounterView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBounds = new Rect();
        setOnClickListener(this);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setColor(Color.BLUE);
        canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
        mPaint.setColor(Color.YELLOW);
        mPaint.setTextSize(30);
        String text = String.valueOf(mCount);
        mPaint.getTextBounds(text, 0, text.length(), mBounds);
        float textWidth = mBounds.width();
        float textHeight = mBounds.height();
        canvas.drawText(text, getWidth() / 2 - textWidth / 2, getHeight() / 2
                + textHeight / 2, mPaint);
    }

    @Override
    public void onClick(View v) {
        mCount++;
        invalidate();
    }

}

 

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.example.customview.CounterView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true" />

</RelativeLayout>

 

自定义View的学习(一) 自绘制控件

相关文章:

  • 2021-10-01
  • 2022-01-18
  • 2021-06-12
  • 2022-01-12
  • 2021-09-25
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
猜你喜欢
  • 2021-07-08
  • 2022-01-04
  • 2021-08-09
  • 2022-12-23
  • 2021-09-27
  • 2021-11-19
  • 2021-05-18
相关资源
相似解决方案