Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
610 views
in Technique[技术] by (71.8m points)

android - How to set Ripple effect on a LinearLayout programmatically?

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" >

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

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

... 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use this way.

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...