Android Lollipop CardView의 파급 효과


191

여기 에 Android 개발자 페이지에 설명 된대로 활동 XML 파일에서 android : backgound 속성을 설정하여 만지면 파급 효과를 표시하도록 CardView를 얻으려고 하지만 작동하지 않습니다. 애니메이션은 전혀 없지만 onClick의 메소드가 호출됩니다. here 제안 된대로 ripple.xml 파일을 만들려고 했지만 동일한 결과를 보았습니다 .

활동의 XML 파일에 표시되는 CardView :

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="155dp"
    android:layout_height="230dp"
    android:elevation="4dp"
    android:translationZ="5dp"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:onClick="showNotices"
    android:background="?android:attr/selectableItemBackground"
    android:id="@+id/notices_card"
    card_view:cardCornerRadius="2dp">

</android.support.v7.widget.CardView> 

나는 안드로이드 개발에 비교적 익숙하지 않으므로 몇 가지 명백한 실수를했을 수도 있습니다.

답변:


593

다음을 추가해야합니다 CardView.

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

8
잔물결 효과가있는 롤리팝에서 작동하지만 구형 플랫폼에서 실행될 때만 단색을 나타냅니다. 나를 위해 충분히 좋은 :)
— mach

16
약간의 관찰 : 나는 클릭 가능한 속성이 필요하지 않으며 심지어 어떤 것들을 깨뜨릴 수 있다고 언급했다! 클릭 가능한 CardViews로 채워진 GridView가 있었고 리스너가 제대로 작동하지 않았습니다. XML에서 클릭 가능한 태그를 제거했으며 이제 모든 것이 완벽하게 작동합니다.
— Joaquin Iurchuk

2
클릭 가능한없이 @joaquin, 그것은 단지 중심에서 발생하는 리플의 원인
— frostymarvelous

2
?android:attr/selectableItemBackground필요 API 레벨 11
— Pratik Butani

9
없이 작업 android:clickable="true".
— Sean

30

이 두 줄 코드를 XML보기에 추가하여 cardView에 파급 효과를 줄 수 있습니다.

android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"

대박! foreground매력처럼 사용자 정의 배경보기와 함께 작동합니다! 좋은!
— sud007

24

나는 cardview에 파급 효과를 얻었습니다.

<android.support.v7.widget.CardView 
    xmlns:card_view="http://schemas.android.com/apk/res-auto" 
    android:clickable="true" 
    android:foreground="@drawable/custom_bg"/>

위의 코드에서 볼 수있는 custom_bg의 경우 lollipop (drawable-v21 패키지) 및 pre-lollipop (drawable package) 장치에 대한 xml 파일을 정의해야합니다. drawable-v21 패키지의 custom_bg의 코드는 다음과 같습니다.

<ripple 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:attr/colorControlHighlight">
<item
    android:id="@android:id/mask"
    android:drawable="@android:color/white"/>
</ripple>

드로어 블 패키지의 custom_bg의 경우 코드는 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true">
    <shape>
        <solid android:color="@color/colorHighlight"></solid>
    </shape>
</item>
<item>
    <shape>
        <solid android:color="@color/navigation_drawer_background"></solid>
    </shape>
</item>
</selector>

롤리팝 이전 기기에서는 클릭 효과가 견고하고 롤리팝 기기에서는 카드보기에 파급 효과가 있습니다.


1
안녕하세요, CardView의 전경에 선택기 (또는 리플)를 적용하여 CardView 자체의 어린이를 차단합니다.- stackoverflow.com/ questions/33763403/ … 아니면 아무것도 빠뜨릴까요? 감사.
— Cheok Yan Cheng

@CheokYanCheng : 나는 당신과 같은 문제에 직면하고 있지 않지만 개인적인 경험에서 cardView에는 롤리팝에 대한 몇 가지 버그가 있다고 말합니다. 롤리팝 이전에 cardview : elevation 속성을 사용하지 마십시오. 위의 내용은 저와 다른 공증인에게 적합합니다.
— Rahul Ahuja

colorHighlight & navigation_drawer_background의 가치가 무엇인지 알고 싶습니다. 투명하지 않고 자신이 정의한 색상을 사용한 경우에도 카드의 자녀를 볼 수 있습니까?
— Cheok Yan Cheng

@CheokYanCheng : 값은 다음과 같습니다. <color name = "navigation_drawer_background"> ​​# FFFFFF </ color> <color name = "colorHighlight"> # FF8A65 </ color>
— Rahul Ahuja

나는 나의 사건을 위해 일하지 않는다. 선택기를 포 그라운드로 사용합니다. 예상대로, 카드보기 포 그라운드로 사용되는 고체 화이트 컬러 (navigation_drawer_background)는 모든 어린이의 가시성을 차단합니다 - i.imgur.com/CleYh5B.png 이다가 전경으로 선택을 적용하지 않고처럼 보이게하는 방법 - i.imgur합니다. com / ZXk5Aoq.png
— Cheok Yan Cheng

14

리플 효과는 사용중인 appcompat 지원 라이브러리에서 생략되었습니다. 잔물결을 보려면 Android L 버전을 사용하고 Android L 기기에서 테스트하십시오. AppCompat v7 사이트 당 :

"롤리팝 이전에 잔물결이없는 이유는 무엇입니까? RippleDrawable을 원활하게 실행할 수있는 많은 것들이 Android 5.0의 새로운 RenderThread입니다. 이전 버전의 Android에서 성능을 최적화하기 위해 RippleDrawable을 남겨 두었습니다."

이 링크를 확인 여기를 대한 추가 정보를 원하시면


그게 다야. 감사!
— AkraticCritic

39
그렇다면 Android Lollipop 용 cardView에 파급 효과를 어떻게 적용 하시겠습니까?
— 안드로이드 개발자

따라서 appcompat를 사용하는 이전 버전과의 호환성 또는 Android 코어의 클래스를 사용하지만 API 21로 제한하는 모든 새로운 효과를 갖는지 여부를 결정해야합니까?
— Urs Reupke

21+ 용 APK 2 개와 <21 개용 APK 2 개를 만들 수도 있습니다. 또는 21+ 이후로 코드를 나누면 supportActionbar 등을 사용하지 않을 것입니다.
— Mathijs Segers

1
이것이 바로 "순수한"Android L 애플리케이션 작성이 현재로서는 불가능한 이유입니다. 2015 년 7 월 기준으로 Android 사용자 기반의 12 %를 타겟팅합니다.
— Glenn Bech

10

minSdkVersion작업중인 앱 이 레벨 9 인 경우 다음을 사용할 수 있습니다.

android:foreground="?selectableItemBackground"
android:clickable="true"

대신 레벨 11부터 다음을 사용합니다.

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

설명서에서 :

clickable- 이보기가 클릭 이벤트에 반응하는지 여부를 정의합니다. 부울 값 ( "true"또는 "false")이어야합니다.

포 그라운드 -컨텐츠 위에 그릴 드로어 블을 정의합니다. 오버레이로 사용할 수 있습니다. 중력이 채워지도록 설정된 경우 전경 드로어 블은 내용의 패딩에 참여합니다.


android : foreground = "? android : attr / selectableItemBackground"사용은 AndroidX 호환성을 위해 작동했습니다. 감사합니다!
— dianakarenms

6

나를 위해 foregroundto를 추가 CardView해도 작동하지 않습니다 (이유를 알 수 없음 : /)

자식 레이아웃에 동일하게 추가하면 트릭이 발생했습니다.

암호:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:focusable="true"
    android:clickable="true"
    card_view:cardCornerRadius="@dimen/card_corner_radius"
    card_view:cardUseCompatPadding="true">

    <LinearLayout
        android:id="@+id/card_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:foreground="?android:attr/selectableItemBackground"
        android:padding="@dimen/card_padding">

    </LinearLayout>
</android.support.v7.widget.CardView>

2
왜냐하면 아이가 이벤트를 가로 채기 때문입니다. 카드 뷰에 패딩을 추가하는 것과 같은 것을 시도하고 (20dp와 같은 것) 패딩이있는 부분을 클릭하면 아이가 없어도 파급 효과가 나타납니다 전경 속성 세트
— Cruces

1
새로운 머티리얼 컴포넌트 com.google.android.material.card.MaterialCardView를 사용하여 저에게도 효과가있었습니다. 클릭 할 수있는 속성없이 전경에서 선택 가능한 항목 배경으로 내부 제약 조건 레이아웃에 적용된 높이 및 잔물결을 조정하기 위해 카드보기에 대한 높이 stateListAnimator가 있습니다.
— Patty P

지금은 기억이 나지 않지만 클릭 이벤트에 반응하지 않도록 하위 뷰를 설정하는 방법이 있습니다.
— 누군가가 어딘가에

3

Button, Linear Layout 또는 CardView와 같은 뷰의 매력처럼이 두 가지 코드 작업을 추가하십시오.이 두 줄을 넣고 마술을보십시오 ...

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

2

CardView에 모든 어댑터 항목의 구성 요소를 포함하는 RelativeLayout 또는 LinearLayout과 같은 루트 레이아웃이있는 경우 해당 루트 레이아웃에서 배경 속성을 설정해야합니다. 처럼:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="122dp"
android:layout_marginBottom="6dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
card_view:cardCornerRadius="4dp">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/touch_bg"/>
</android.support.v7.widget.CardView>

2

안드로이드 Cardview제어를 위한 리플 이벤트 :

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:foreground="?android:attr/selectableItemBackground"
    android:clickable="true"
    android:layout_marginBottom="4dp"
    android:layout_marginTop="4dp" />

1

AppCompat에 만족하지 않아서 자체 CardView와 백 포트 리플을 작성했습니다. Gingerbread와 함께 Galaxy S에서 실행 중이므로 확실히 가능합니다.

Galaxy S의 잔물결 데모

자세한 내용은 소스 코드를 확인하십시오 .


링크가 끊어졌습니다
— temirbek

1

XML에 다음을 추가하십시오.

android:clickable="true"
android:focusable="true"
android:background="?android:attr/selectableItemBackground"

그리고 어댑터에 추가하십시오 (귀하의 경우)

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val attrs = intArrayOf(R.attr.selectableItemBackground)
            val typedArray = holder.itemView.context.obtainStyledAttributes(attrs)
            val selectableItemBackground = typedArray.getResourceId(0, 0)
            typedArray.recycle()

            holder.itemView.isClickable = true
            holder.itemView.isFocusable = true
            holder.itemView.foreground = holder.itemView.context.getDrawable(selectableItemBackground)
        }
    }

0

프로그래밍 방식으로 작성된 CardView (또는 내 경우에는 CardView를 확장하는 사용자 정의보기)에서 작동하지 않는 리플 효과 문제에 대한 해결책을 찾고있는 사람들은 RecyclerView에 표시됩니다. 기본적으로 XML 레이아웃 파일에서 선언적으로 다른 답변에 언급 된 XML 속성을 선언하는 것은 프로그래밍 방식으로 작성된 CardView 또는 사용자 정의 레이아웃에서 작성된 XML 속성 (루트보기가 CardView 또는 merge 요소를 사용하는 경우에도)에서 작동하지 않는 것 같습니다. 프로그래밍 방식으로 다음과 같이 설정해야합니다.

private class MadeUpCardViewHolder extends RecyclerView.ViewHolder {
    private MadeUpCardView cardView;

    public MadeUpCardViewHolder(View v){
        super(v);

        this.cardView = (MadeUpCardView)v;

        // Declaring in XML Layout doesn't seem to work in RecyclerViews
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int[] attrs = new int[]{R.attr.selectableItemBackground};
            TypedArray typedArray = context.obtainStyledAttributes(attrs);
            int selectableItemBackground = typedArray.getResourceId(0, 0);
            typedArray.recycle();

            this.cardView.setForeground(context.getDrawable(selectableItemBackground));
            this.cardView.setClickable(true);
        }
    }
}

이 부분에 대한 대답 은 어디 MadeupCardView extends CardView입니까 ?TypedArray


0
  android:foreground="?android:attr/selectableItemBackgroundBorderless"
   android:clickable="true"
   android:focusable="true"

작동하는 API 21 만 사용 하고이 목록 행 카드보기를 사용하지 마십시오.


0

대신 Material Cardview를 사용하면 Cardview를 확장하고 기본 클릭 가능한 효과를 포함한 여러 가지 새로운 기능을 제공합니다.

<com.google.android.material.card.MaterialCardView>

...

</com.google.android.material.card.MaterialCardView>

의존

implementation 'com.google.android.material:material:1.0.0'
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.