我有一个自定义 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/