Android自定义 View 背景选择

标签 android background selection custom-view

我有一个自定义 View :

public class MyView extends RelativeLayout {

    private LayoutInflater inflater;

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.my_view, this);
    }
}

用一个 xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"/>

我还有一个背景选择器:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:drawable="@drawable/top_press" /> <!-- pressed -->
     <item android:drawable="@drawable/top_idle" /> <!-- default -->
 </selector>

当我使用选择器作为背景时,它不起作用:

<com.example.MyView style="@style/someStyle" 
    android:background="@drawable/item_selector_top" android:clickable="true"/>

但是,当我从内部 xml 中放置背景时,它确实有效:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:background="@drawable/item_selector_top"/>

有人知道为什么吗?

最佳答案

您应该将父级的状态传递给自定义 View 的子级。使用:

android:duplicateParentState="true"

注意:如果您的自定义 View 具有像 A->B->C 这样的高级层次结构,并且您希望“C” View 处理状态行为,您也应该将 duplicateParentState 放入“A”和“B” View 。

关于Android自定义 View 背景选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8239413/

相关文章:

android - 覆盖 RxAndroid 调度程序以进行测试

vim - 如何复制选区并将其放置在选区上方或下方

Eclipse 相当于 Visual Studio ALT + 选择多行文本

javascript - CSS 只允许在网页上选择文本?

android - 我是否必须使用配置 Google Play 服务的同一 Google 帐户发布我的应用程序?

android - 约束布局而不是相对布局

jquery - CSS背景图像预加载器

html - 将鼠标悬停在图像上时更改 div 的背景图像

java - 将 sqLite DB 中的数据显示到不同的 TextView 中

python - 从 django 执行不能被 web 服务器中断的后台进程