点击View时出现背景,并且出现背景的过程是线性具有动画效果的
时间: 2023-08-22 16:09:38 浏览: 31
要实现点击 `View` 时出现背景,并且出现背景的过程是线性具有动画效果的,可以使用 `StateListDrawable` 和 `Animator`。下面是一个示例代码:
1. 创建一个 `res/drawable/clickable_bg.xml` 文件,定义 `StateListDrawable`:
```xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="@color/colorAccent" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
</shape>
</item>
</selector>
```
在上面的示例中,当 `View` 被按下时,背景颜色为 `colorAccent`,否则为 `colorPrimary`。
2. 在你的 `Activity` 或 `Fragment` 中,为 `View` 设置点击事件并且使用 `Animator` 来实现动画:
```java
// 获取要设置点击事件的 View 对象
View view = findViewById(R.id.my_view);
// 创建渐变动画
AnimatorSet animatorSet = new AnimatorSet();
ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(view, "alpha", 0.5f, 1.0f);
ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(view, "scaleX", 0.9f, 1.0f);
ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(view, "scaleY", 0.9f, 1.0f);
animatorSet.playTogether(alphaAnimator, scaleXAnimator, scaleYAnimator);
animatorSet.setDuration(200);
// 设置点击事件
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setBackground(ContextCompat.getDrawable(MainActivity.this, R.drawable.clickable_bg));
animatorSet.start();
}
});
```
在上面的示例中,当 `View` 被点击时,设置背景为 `clickable_bg.xml` 中定义的 `StateListDrawable`,并且启动 `AnimatorSet` 来实现渐变动画。
这样,当用户点击 `View` 时,就会出现背景,并且出现背景的过程是线性具有动画效果的。