Android - 在 TextView 上设置按下状态和边框 - 只有一个背景

标签 android android-drawable android-selector

我有 3 个 TextView 垂直堆叠在 LinearLayout 中

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:textSize="@dimen/text_size_large"
        android:text="Item1"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:textSize="@dimen/text_size_large"
        android:text="Item2"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:textSize="@dimen/text_size_large"
        android:text="Item3"/>
</LinearLayout>

我可以将可绘制对象应用于背景属性来渲染边框

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke android:width="1dp" android:color="@color/pale_grey" />
            <padding android:left="24dp" android:right="24dp" 
                       android:top="12dp" android:bottom="12dp" />
        </shape>
    </item>
</layer-list>

我还可以通过可绘制对象将选择器应用到背景属性,以便 TextView 根据“按下”等状态更改颜色。然而,只有一个背景属性。

我不相信我可以在同一个可绘制对象中应用 xml 和 xml。因此,我是否需要在每个 TextView 周围包裹一个布局元素,以便可以应用另一个背景?

看起来谷歌通过将边框、填充和背景颜色包含在一个可绘制的 patch-9 图像中来解决这个问题。我希望我不需要这样做

谢谢

最佳答案

在选择器中使用呈现边框的 XML 设置按下和未按下的状态

示例:

<selector     xlmns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/border_unpressed" android:state_pressed="false"/> 
 <item android:drawable="@drawable/border_pressed" android:state_pressed="true"/>
 <item android:drawable="@drawable/border_unpressed" />

</selector>

注意: 确保设置 TextView 属性 android:clickable="true"

关于Android - 在 TextView 上设置按下状态和边框 - 只有一个背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26891459/

相关文章:

android - 设置样式后不能点击按钮

android - 在可绘制选择器中更改实体的颜色

android - 如何将 PhoneGap - Android 设置过程作为一步构建?

android - Android中的Bitmap和Drawable有什么区别?

java - 忽略 AndroidX 并希望在 Android Studio 3.2 中单独使用 android 支持库

android - 如何在android studio的可绘制列表中显示图标

android - 每次进入 ListView 屏幕时,如何使第一个项目默认聚焦在ListView中?

java - 在平板电脑上滚动列表后意外重用了选定的列表项背景颜色

android - 如何从 android-studio 中包外的目录访问 .java 文件?

Android- 从文件中播放 gif 动画