Android中selector怎么使用

在Android中,selector用于在不同的状态下显示不同的资源。您可以按照以下步骤使用selector:

在res/drawable文件夹中创建一个XML文件,命名为selector.xml(也可以自定义文件名)。

在selector.xml中定义要使用的不同状态下的资源。例如:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/pressed_background" android:state_pressed="true"/>
    <item android:drawable="@drawable/normal_background"/>
</selector>

在上面的例子中,当按钮被按下时,会使用pressed_background资源,否则会使用normal_background资源。

在布局文件中使用selector。例如,将selector作为背景应用于一个按钮:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/selector"
    android:text="Button" />

在上面的例子中,按钮的背景将根据按钮的状态来更新。

请注意,selector可以用于不同的属性,如background、textColor等。您可以根据需要在不同的属性中使用selector。

阅读剩余
THE END