如何以编程方式在 LinearLayout 上设置波纹效果? [英] How to set Ripple effect on a LinearLayout programmatically?

查看:31
本文介绍了如何以编程方式在 LinearLayout 上设置波纹效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将背景 android.R.attr.selectableItemBackground 设置为 LinearLayout.使用 XML 时没有问题(它有效)

I want to set the background android.R.attr.selectableItemBackground to a LinearLayout. When using XML there are no problems (it works)

<LinearLayout
    android:id="@+id/llMiner"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true" >

...但我必须在java代码中做到这一点,所以我试过这个

... but I have to do this in java code, so I've tried this

llMiner.setClickable(true);
llMiner.setBackgroundResource(android.R.attr.selectableItemBackground);

... 它不起作用,事实上我在第二行得到一个 NotFoundException.所以在我尝试了这个变体之后,我认为资源是一种颜色.

... and it doesn't work, infact I get a NotFoundException on this second line. So after I've tried this variant thinking that the resource is a Color.

llMiner.setClickable(true);
llMiner.setBackgroundColor(android.R.attr.selectableItemBackground);

这个不会启动异常,但是...不起作用(按下时背景没有变化,但按下时状态会发生变化)...有什么建议吗?

This one doesn't launch exception, but... doesn't work (there are no changing of background when pressing, but the state change in pressed as it have to do)... any suggestion?

推荐答案

你可以这样使用.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    // If we're running on Honeycomb or newer, then we can use the Theme's
    // selectableItemBackground to ensure that the View has a pressed state
    TypedValue outValue = new TypedValue();
    this.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
    textView.setBackgroundResource(outValue.resourceId);
}

这篇关于如何以编程方式在 LinearLayout 上设置波纹效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆