Android如何使用自定义选择器

时间:2018-02-04 18:47:30

标签: android textview selector ripple

我正在创建一个代表键盘的自定义视图,布局非常简单,它只是放置在表格布局中的9个textView。我希望当我按下其中一个键时,会出现漂亮的圆形波纹效果。

这是我到目前为止所做的事情

drawable / button_selector.xml(颜色/选中是浅蓝色)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/selected" android:state_pressed="true" android:state_selected="false"/>
</selector>

style.xml(我在attrs.xml中放了selectable_bg_borderless)

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    [....]
    <item name="selectable_bg_borderless">@drawable/btn_selector</item>
</style>

<style name="AppTheme.Text.KeypadKey" parent="@style/AppTheme.Text">
        [..]
        <item name="android:background">?selectable_bg_borderless</item>
        [..]
</style>

布局/ view_keypad.xml

<TableRow
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1.0"
        android:gravity="center">

        <TextView
            android:id="@+id/key_1"
            style="@style/AppTheme.Text.KeypadKey"
            android:text="1"/>

        [....]
    </TableRow>

然而,当我按下“1”时,我确实有一个蓝色的背景,但它是一个原始而简单的方形..我怎么能达到这样的目的?

enter image description here

1 个答案:

答案 0 :(得分:1)

确保主题为appcompat,只需将视图的背景属性更改为

即可
android:background="?selectableItemBackgroundBorderless