Переопределение Android-L CardView state_pressed для старых версий Android
В последнем Android SDK теперь появился новый CardView, я заменил свой старый CustomCardView новой версией, но при работе с ним в более старых версиях Android я вижу, что state_pressed
и state_focused
- уродливые квадраты которые отображаются выше CardView...
Кто-нибудь знает, как я мог бы эмулировать следующее в новом CardView, но только при использовании более старых версий Android?
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:enterFadeDuration="150"
android:exitFadeDuration="150" >
<item android:state_pressed="true"
android:drawable="@drawable/card_on_press"/>
<item android:state_focused="true" android:state_enabled="true"
android:drawable="@drawable/card_on_focus"/>
<item android:state_enabled="true"
android:drawable="@drawable/card_default"/>
<item android:state_enabled="false"
android:drawable="@drawable/card_on_press"/>
</selector>
И для тех, кто вас интересует, это CardView, который я использую сейчас:
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/CardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:foreground="?android:attr/selectableItemBackground"
android:onClick="RunSomeMethod"
card_view:cardCornerRadius="4dp"
android:focusable="true"
android:elevation="2dp">
<LinearLayout
android:id="@+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:focusable="false"
android:visibility="visible">
</LinearLayout>
</android.support.v7.widget.CardView>
Ответы
Ответ 1
Исправлено с помощью следующего кода:
значения-v21\styles.xml:
<style name="CardViewStyle" parent="CardView.Light">
<item name="android:foreground">?android:attr/selectableItemBackground</item>
</style>
значения\styles.xml:
<style name="CardViewStyle" parent="android:Widget.TextView">
<item name="android:foreground">@drawable/card</item>
</style>
Карта из макета \main_layout.xml:
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/Card_View"
style="@style/CardViewStyle"
android:layout_width="480dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
card_view:cardCornerRadius="4dp"
android:elevation="2dp">
Это позволит вам предлагать анимацию в v21 +, но также предлагает альтернативные анимации в pre-v21, а не в большом синем/сером квадрате.
Вот файл card.xml, который я использую как подходящий для тех, кто вас интересует:
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:enterFadeDuration="150"
android:exitFadeDuration="150" >
<item android:state_pressed="true"
android:drawable="@drawable/card_on_press"/>
<item android:state_focused="true" android:state_enabled="true"
android:drawable="@drawable/card_on_focus"/>
<item android:state_enabled="true"
android:drawable="@drawable/card_default"/>
<item android:state_enabled="false"
android:drawable="@drawable/card_on_press"/>
</selector>
Примечание:
Drawable default будет прекрасным как прозрачный элемент, так как CardView предоставляет фон по умолчанию для всех версий Android.
Ответ 2
Возможно, библиотека была обновлена, но когда я использую следующее, она выглядит отлично в старых версиях Android.
Вы можете использовать "CardView.Dark" и CardView.Light '
(будет автоматически генерироваться с помощью библиотеки поддержки карт)
В ваших значениях /styles.xml
<style name="CardViewStyle.Light" parent="CardView.Light">
<item name="android:foreground">?android:attr/selectableItemBackground</item>
</style>
<style name="CardViewStyle.Dark" parent="CardView.Dark">
<item name="android:foreground">?android:attr/selectableItemBackground</item>
</style>
Макеты для CardView
Создайте два макета, один для темного и один для освещения. Они будут включать в себя следующие виды карточек:
<android.support.v7.widget.CardView
android:id="@+id/my_card_view"
style="@style/CardViewStyle.Light"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:cardCornerRadius="2dp"
android:elevation="2dp">
... other layout stuff ...
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="@+id/my_card_view"
style="@style/CardViewStyle.Dark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:cardCornerRadius="2dp"
android:elevation="2dp">
... other layout stuff ...
</android.support.v7.widget.CardView>
Обратите внимание на переключение стиля в каждом CardView.
Другие настройки
Если вы хотите настроить цвет, а не только черный или белый, вы можете использовать следующее:
Чтобы получить DrawView CardView, вы можете использовать:
View cardView = findViewById(R.id.my_card_view);
Drawable cardViewDrawable cardView.getBackground();
convertIcon(setViewBackground(cardView, cardViewDrawable));
My 'convertIcon' - это просто следующее:
/**
*
* @param drawable e.g. "getResources().getDrawable(R.drawable.my_drawable)"
* @param tint e.g. "Color.parseColor(lightTitlebarFg)"
* @return Drawable
*
*/
public static Drawable convertIcon(Drawable drawable, int tint) {
ColorFilter filter = new PorterDuffColorFilter(tint, PorterDuff.Mode.SRC_ATOP);
drawable.setColorFilter(filter);
return drawable;
}
My setViewBackground - это просто следующее:
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressWarnings("deprecation")
public static void setViewBackground(View view, Drawable drawable){
if (UIUtils.isJB()) {
view.setBackground(drawable);
} else {
view.setBackgroundDrawable(drawable);
}
}
StateListDrawable
Если вы хотите создать StateListDrawable программно, можете использовать следующее:
StateListDrawable states = new StateListDrawable();
states.addState(new int[] { android.R.attr.state_focused }, focusedDrawable);
states.addState(new int[] { android.R.attr.state_activated }, activatedDrawable);
states.addState(new int[] { android.R.attr.state_enabled }, defaultDrawable);
states.addState(new int[] {}, defaultDrawable);
Ответ 3
Вот код, который я использовал в файле card_on_press.xml, который хранится в выпадающей папке проекта:
<item>
<shape>
<padding
android:bottom="0dp"
android:left="0dp"
android:right="0dp"
android:top="0dp" />
<solid android:color="@color/transparent" />
</shape>
</item>
<item>
<shape>
<padding
android:bottom="0dp"
android:left="0dp"
android:right="0dp"
android:top="0dp" />
<solid android:color="@color/card_shadow_1_on_press" />
<corners android:radius="8dp" />
</shape>
</item>
<item>
<shape>
<padding
android:bottom="0dp"
android:left="0dp"
android:right="0dp"
android:top="0dp" />
<solid android:color="@color/card_shadow_2_on_press" />
<corners android:radius="8dp" />
</shape>
</item>
<!-- Background -->
<item>
<shape>
<solid android:color="@color/card_background_on_press" />
<corners android:radius="8dp" />
</shape>
</item>