Hen*_*ian 54 xml android android-layout android-cardview
在xml中,我经常这样做来模拟onClick
效果:
<android.support.v7.widget.CardView
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?selectableItemBackground">
...
</android.support.v7.widget.CardView>
Run Code Online (Sandbox Code Playgroud)
有没有办法?selectableItemBackground
在java中访问?
Ami*_*ela 126
对于appcompat你可以使用,
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
cardView.setBackgroundResource(outValue.resourceId);
Run Code Online (Sandbox Code Playgroud)
Nic*_*hel 20
我在那儿!对于那些与Kotlin一起工作的人,这里有一些扩展功能,可以在Android View类型上添加Ripple:
private fun View.addRipple() = with(TypedValue()) {
context.theme.resolveAttribute(android.R.attr.selectableItemBackground, this, true)
setBackgroundResource(resourceId)
}
private fun View.addCircleRipple() = with(TypedValue()) {
context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, this, true)
setBackgroundResource(resourceId)
}
Run Code Online (Sandbox Code Playgroud)
对于 Kotlin 我正在使用
binding.yourCoolView.apply {
background = with(TypedValue()) {
context.theme.resolveAttribute(
androidx.appcompat.R.attr.selectableItemBackground, this, true)
ContextCompat.getDrawable(context, resourceId)
}
}
Run Code Online (Sandbox Code Playgroud)
我一直在寻找相同的解决方案。我对这个答案做了些微修改,使其更适合提出的问题。从构造函数中调用以下代码。
private void setClickableAnimation(Context context)
{
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(
android.R.attr.selectableItemBackground, outValue, true);
setForeground(getDrawable(context, outValue.resourceId));
}
Run Code Online (Sandbox Code Playgroud)
对于使用 Kotlin 的人来说,这是 @Nicolas 答案的扩展版本。如果您正在使用CardView
,您需要更改的是foreground
,而不是background
。
代码
fun View.addBackgroundRipple() = with(TypedValue()) {
context.theme.resolveAttribute(android.R.attr.selectableItemBackground, this, true)
setBackgroundResource(resourceId)
}
fun View.addBackgroundCircleRipple() = with(TypedValue()) {
context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, this, true)
setBackgroundResource(resourceId)
}
fun View.addForegroundRipple() = with(TypedValue()) {
context.theme.resolveAttribute(android.R.attr.selectableItemBackground, this, true)
foreground = ContextCompat.getDrawable(context, resourceId)
}
fun View.addForegroundCircleRipple() = with(TypedValue()) {
context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, this, true)
foreground = ContextCompat.getDrawable(context, resourceId)
}
Run Code Online (Sandbox Code Playgroud)
用法
// Background ripple
linearLayout.addBackgroundRipple()
// Foreground ripple
cardView.addForegroundRipple()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19486 次 |
最近记录: |