首页 > 解决方案 > Android - 如何将 selectableItemBackground 应用于整个 ListView 项目?

问题描述

我是 Android 新手,现在正在编写我的第一个应用程序。我有一个 ListView 呈现一系列项目,每个项目都有多个 TextView。我希望 ListView 中的每个项目都可以点击,并为点击设置动画。动画是我正在努力解决的问题。

我有 selectableItemBackground 属性,它可以在 TextView-by-TextView 的基础上完美运行。但是,这意味着点击动画只出现在特定的 TextView 上,而我希望它出现在整个列表项本身上。

这是我的安卓视图。我知道这种行为是由于我将 selectableItemBackground 属性放在 TextView 元素上引起的,我只是想不出还有什么地方可以达到我想要的效果。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center">
    <TextView
        android:id="@+id/past_game_update_timestamp"
        android:foreground="?android:attr/selectableItemBackground"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:clickable="true"
        android:padding="@dimen/small_padding"
        android:textSize="@dimen/small_font_size" />
    <TextView
        android:id="@+id/past_game_start_timestamp"
        android:foreground="?android:attr/selectableItemBackground"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:clickable="true"
        android:padding="@dimen/small_padding"
        android:textSize="@dimen/small_font_size" />
</LinearLayout>

标签: android

解决方案


作为我从你的问题中理解的一部分。您是否希望整个视图都具有 onClick 动画。为此,您有两个选择:

在大多数情况下,您应该在视图 XML 中应用此功能,方法是将视图背景指定为:

  1. ?android:attr/selectableItemBackground为有界波纹。
  2. ?android:attr/selectableItemBackgroundBorderless延伸到视野之外的涟漪。它将被绘制在最近的具有非空背景的视图的父级上。

注意:selectableItemBackgroundBorderless 是 API 级别 21 中引入的新属性。

请检查选项 2。


推荐阅读