需求
点击父布局区域,2个子view有press状态,且ACTION_UP时要有select状态
大概就是上面这个图的状态
解决
xml布局
<RelativeLayout
android:id="@+id/rl_device"
android:focusableInTouchMode="true"
style="@style/tab_item_layout">
<ImageButton
android:id="@+id/ib_device"
style="@style/btn_tab"
android:clickable="false"
android:focusable="false"
android:src="@drawable/selector_tab_device" />
<View
android:id="@+id/line_device"
style="@style/tab_line"
android:clickable="false"
android:focusable="false" />
</RelativeLayout>
重点代码是在父布局加入
android:focusableInTouchMode="true"
子view加入
android:clickable="false
android:focusable="false"
代码修改
这样布局会带来一个问题,在监听RelativeLayout的点击事件时,第一次点击不会有onClick的回调,有兴趣的同学可以去看下onTouchEvent的源码,如果ACTION_UP是在focusableInTouchMode,并且没获得焦点,会去获得焦点;当下一次ACTION_UP时,才会调用 performClick()。
所以我们需要以下修改
rlDevice.setOnTouchListener(new onTouchListenerImpl());
class onTouchListenerImpl implements OnTouchListener {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP && !v.isFocused()) {
v.performClick();
}
return false;
}
};