LinearLayout获取焦点并响应点击事件监听

来源:互联网 发布:1688端口是干嘛的 编辑:程序博客网 时间:2024/06/05 03:33

LinearLayout控件

 <LinearLayout            android:id="@+id/gj_recruit"            android:layout_width="match_parent"            android:layout_height="50dip"            android:layout_marginBottom="17dip"            android:background="@drawable/toggle_fillet"            android:focusableInTouchMode="true"            android:clickable="true"            android:orientation="horizontal"            android:padding="7dip">
1、通过background切换获取焦点和失去焦点的样式,在drawable中新建一个toggle_fillet.xml。

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_focused="true">        <shape>            <solid android:color="@color/gj_green" />            <corners android:bottomLeftRadius="25dp" android:bottomRightRadius="25dp" android:topLeftRadius="25dp" android:topRightRadius="25dp" />            <stroke android:width="1dp" android:color="#46c37b" />        </shape>    </item>    <item>        <shape>            <solid android:color="@color/grid_state_pressed" />            <corners android:bottomLeftRadius="25dp" android:bottomRightRadius="25dp" android:topLeftRadius="25dp" android:topRightRadius="25dp" />            <stroke android:width="1dp" android:color="@color/gj_green" />        </shape>    </item></selector>
没有属性的item为默认的样式,state_fouchsed为获取焦点时的样式(item属性参考:点击打开链接)。

2、设置focusableInTouchMode和clickable为true,但是设置focusableInTouchMode为true的时候会存在一个问题,第一次点击控件的时候,它将取得焦点,第二次点击的时候才去响应点击事件。解决方案:implementsView.OnTouchListener,继承touch事件,当松开的时候去执行点击事件。

2.1、判断touch事件的状态,松开时执行点击事件:

 @Override    public boolean onTouch(View v, MotionEvent event) {        if (event.getAction() == MotionEvent.ACTION_UP){            onClick(v);        }        return false;    }










阅读全文
4 0