android - 有什么方法可以让 Ripple 效果的颜色在 Android 中是动态的?
问题描述
我在我的应用程序的用户界面中对可点击元素使用了涟漪效应:
<?xml version="1.0" encoding="utf-8"?>
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/MenuGray">
<item>
<shape
android:shape="rectangle">
</shape>
</item>
</ripple>
问题是我希望对具有不同背景颜色的元素产生连锁反应。有什么办法可以让波纹颜色变成动态的,所以它会比被点击的元素更暗,还是我需要为每个具有不同背景颜色的元素设置多个波纹.xml 文件?
解决方案
如果你加载RippleDrawable
你应该能够设置颜色。
公共无效 setColor(ColorStateList 颜色)
设置波纹颜色。
这是一个更改RippleDrawable
几个TextViews
.
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView);
setRippleColor(textView, Color.RED);
textView = findViewById(R.id.textView2);
setRippleColor(textView, getResources().getColor(android.R.color.holo_blue_light));
}
private void setRippleColor(View view, int color) {
RippleDrawable drawable = (RippleDrawable) view.getBackground();
ColorStateList stateList = new ColorStateList(
new int[][]{new int[]{android.R.attr.state_pressed}},
new int[]{color}
);
drawable.setColor(stateList);
view.setBackground(drawable);
}
}
activity_main.xml
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ripple_drawable"
android:clickable="true"
android:focusable="true"
android:text="Make it red"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/ripple_drawable"
android:clickable="true"
android:focusable="true"
android:text="Make it blue"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>
波纹绘图.xml
<ripple android:color="@android:color/darker_gray">
<item android:id="@android:id/mask"
android:drawable="@android:color/white" />
</ripple>
您可能还会发现“以编程方式创建任意颜色的 RippleDrawable”很有帮助。
推荐阅读
- c# - ListView图像有时在winform c#中放错位置并消失
- numbers - Nasm 中的打印数字批评
- redirect - 尝试使用查询字符串将子域重定向到域时,IIS URL 重写不起作用
- javascript - Rock, Paper, Scissors 游戏:输入正确的值返回错误的 console.log 消息
- mysql - 求和子查询 MySql
- multithreading - 分析多线程中的上下文切换
- django - Django 与 Heroku-PostgreSQL 数据库水平缩放
- amazon-web-services - ECS 503暂时可用是什么原因?
- blazor - 使用 Javascript 编辑 DOM
- deep-learning - 使用pytorch计算特征中心时GPU内存不够