ProgramingTip

CardView 배경색 상태가 존중되지 않음

bestdevel 2020. 12. 30. 23:53
반응형

CardView 배경색 상태가 존중되지 않음


간단히 말해서 :

CardView의 cardBackgroundColor 속성 (이 경우 ListView 레이아웃에서)의 색상 상태를 어떻게 정의 할 수 있습니까?

(나는 Android L 개발자 미리보기의 RC1, 4.4가 강력 휴대 전화에서 사용하고 있으며 build.gradle에서 "com.android.support-v7 : 21.0.0-rc1"을 사용하고 있습니다.)

더 당신 :

CardView 레이아웃에서 cardCornerRadius 및 cardBackgroundColor를 통해 CardView의 모서리 반경과 배경색을 설정합니다.

그러나 배경색은 예를 들어 목록 항목을 눌렀을 때와 같이 선택 상태를 반영하지 않습니다.

CardView의 내부보기에서 배경색과 관련 상태를 설정하면 존중할 때 CardView에서 정의한 모서리 위에 표시됩니다.

CardView의 cardBackgroundColor의 상태가 존중되는 어떻게 확인할 수 있습니까?

다음은 cardBackgroundColor, colour_with_states.xml에 사용되는 색상입니다.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true"  android:state_enabled="false" android:state_pressed="true" android:color="@android:color/holo_green_dark" />
    <item android:state_focused="true"  android:state_enabled="false"                              android:color="@android:color/holo_green_dark" />
    <item android:state_focused="true"                                android:state_pressed="true" android:color="@android:color/holo_green_dark" />
    <item android:state_focused="false"                               android:state_pressed="true" android:color="@android:color/holo_green_dark" />
    <item android:state_focused="true"                                                             android:color="@android:color/holo_green_dark" />
    <!-- Only this below is seen in the cardview dispaly -->
    <item android:color="@android:color/holo_blue_bright" />
</selector>

그리고 CardView를 사용하는 레이아웃 :

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cardview="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    cardview:cardCornerRadius="10dp"
    cardview:cardBackgroundColor="@color/colour_with_states"
    >

<!-- If we set a background color below, it will overwrite our radius defined above -->
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:text="Lorem ipsum"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItem"
    android:background="@null"
    android:gravity="center_vertical"
    android:paddingTop="8dip"
    android:paddingBottom="8dip"
    android:paddingStart="8dip"
    android:paddingEnd="8dip"
    />

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

이것이 둥글 지 않기 때문에 가장자리가 둥글 지 않기 때문에 다음 CardView과 같이 터치를 추가 할 수 있습니다 .

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="4dp"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground">

    //Nested View ...

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

추가을 android:foreground하고하는 [해석] android:clickable받는 속성 CardView.

또한 android:clickable속성이 모든에 ClickListener를 재정의하므로 해당에 ClickListener 트리거되지 않는다는가 부정적인 부작용이 있습니다 .

최신 정보

CardView 구현의 몇 가지 예가 있습니다.

루프 ( https://github.com/lawloretienne/Loop ) - https://github.com/lawloretienne/Loop/blob/master/app/src/main/res/layout/category_card.xml

QuickReturn ( https://github.com/lawloretienne/QuickReturn ) - https://github.com/lawloretienne/QuickReturn/blob/master/sample/src/main/res/layout/activity_quick_return.xml

업데이트 2

더 많은 연구 끝에 저는 pre-Lollipop을 포함한 모든 API 버전에서 CardViews에 대한 좋은 솔루션을 찾았습니다.

https://medium.com/@etiennelawlor/layout-tips-for-pre-and-post-lollipop-bcb2e4cdd6b2#.9h0v1gmaw


때로는 CardView시각적 터치 피드백을 원할 수 있습니다 . android:foreground="?android:attr/selectableItemBackground"솔루션이 최적입니다.

그러나 drawSelectorOnTop(true)ListView와 함께 사용 하는 것을 고려할 수 있습니다 . 이것은 전혀 변경이 필요하지 않습니다 CardView.

추가 설명이 필요하면 알려주세요.


문제를 해결하는 방법은 다음과 같습니다.

먼저 CustomCardViewextends 라는 사용자 정의 클래스를 만듭니다.CardView

그런 다음 drawableStateChanged()방법을 무시하고 setCardBackgroundColor()카드의 프레스 상태가 변경되면 호출 방법으로 카드 배경색을 변경하십시오.

마지막으로 레이아웃 파일에서 CardView를이 CustomCardView로 바꿉니다.

이 솔루션의 유일한 단점은 Android 5.0 이상에서 cardview가 리플 프레스 효과를 표시 할 수 없다는 것입니다.

내 코드는 다음과 같습니다.

public class CustomCardView extends CardView {

public CustomCardView(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}

public CustomCardView(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub
}

public CustomCardView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    // TODO Auto-generated constructor stub
}

@Override
protected void drawableStateChanged() {
    super.drawableStateChanged();
    if (isPressed()) {
        this.setCardBackgroundColor(getContext().getResources().getColor(R.color.card_view_pressed));
    } else {
        this.setCardBackgroundColor(getContext().getResources().getColor(R.color.card_view_normal));
    }
}

}


내가 사용한 한 가지 해결 방법은 사용자 정의 ViewHolder 내에서 View.OnTouchListener OnTouch () 이벤트 핸들러를 재정 의하여 프로그래밍 방식으로 UI 변경을 수행하는 것입니다.

@Override
public boolean onTouch (View v, MotionEvent event) 
{
    int action = event.getActionMasked();
    if (action == MotionEvent.ACTION_DOWN) 
    {
        mCardView.setCardBackgroundColor(STATE_PRESSED_COLOR);
    } 
    else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) 
    {
        mCardView.setCardBackgroundColor(DEFAULT_COLOR);
    }
    return false;
}

** 카드보기 내부에 선을 추가하기 만하면됩니다 **

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

나는 cardview와 동일한 모서리 반경을 가진 직사각형 모양을 사용했습니다. 그런 다음 xml 드로어 블을 카드 뷰의 내부 뷰에 대한 배경으로 사용했습니다. 카드와 내부 뷰 사이에 여전히 작은 패딩이 있지만 배경은 카드 뷰 모서리 위에 표시되지 않습니다.

여기에 이미지 설명 입력


carBackgroundColor 속성의 정의를 보면 적어도 안드로이드 지원 라이브러리에서는 다음과 같습니다.

<resources>
    <declare-styleable name="CardView">
        <!-- Background color for CardView. -->
        <attr name="cardBackgroundColor" format="color" />
    </declare-styleable>
</resource>

여기서는 cardBackgroundValue의 색상 만 사용한다고 말합니다. 나는 이것이 선택자가 존중되지 않지만 기본값 즉, 떨어짐을 의미한다고 생각합니다. 선택기 하단의 색상.


사용 android:foreground대신에 android:background당신에 <CardView/>. 아래는 CardView의 샘플 코드입니다.

 <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground"
        app:cardCornerRadius="2dp"
        app:cardElevation="2dp">

// others view component 

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

참조 URL : https://stackoverflow.com/questions/25352930/cardview-background-color-states-not-being-respected

반응형