Android studio自定义控件实现鼠标点击图标变大
时间: 2023-11-22 22:54:47 浏览: 30
要实现这个效果,可以通过自定义 View 的方式来实现。具体步骤如下:
1. 自定义一个 View,并重写 onDraw() 方法,在其中绘制一个图标。
2. 在 onDraw() 方法中使用 Paint 对象设置图标的颜色和大小。
3. 在 onTouchEvent() 方法中监听用户的点击事件,在用户点击时设置图标的大小变化。
下面是一个简单的实现示例:
```java
public class IconView extends View {
private Paint mPaint;
private Bitmap mIcon;
private int mIconSize = 100;
private int mIconColor = Color.RED;
private boolean mIsPressed = false;
public IconView(Context context) {
super(context);
init();
}
public IconView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public IconView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mIcon = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制图标
mPaint.setColor(mIconColor);
mPaint.setStyle(Paint.Style.FILL);
int left = (getWidth() - mIconSize) / 2;
int top = (getHeight() - mIconSize) / 2;
int right = left + mIconSize;
int bottom = top + mIconSize;
canvas.drawBitmap(mIcon, null, new Rect(left, top, right, bottom), mPaint);
// 绘制边框
if (mIsPressed) {
mPaint.setColor(Color.GRAY);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(5);
canvas.drawRect(left, top, right, bottom, mPaint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mIsPressed = true;
mIconSize = 120; // 设置图标大小变化
invalidate(); // 刷新 View
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIsPressed = false;
mIconSize = 100; // 恢复图标大小
invalidate();
break;
}
return true;
}
}
```
在布局文件中使用该自定义 View:
```xml
<com.example.IconView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
```
这样,当用户点击该 View 时,图标就会变大,并且边框会出现。