RecyclerView设置的布局如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="@+id/tv_url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:inputType="text"
android:paddingRight="30dp"
android:textSize="15sp"
tools:text="Test" />
</RelativeLayout>
效果图如下:
代码编译运行到机器上,发现点击条目时,只有空白的地方有点击效果,而点击“Text”文本没有触发条目点击效果。
经过调试,发现只要把布局文件中TextView的如下设置去掉即可:
android:inputType="text"
官方是这样说明的:
Attribute android:inputType should not be used with <TextView>: Change element type to <EditText> ? less... (Ctrl+F1)
Using a <TextView> to input text is generally an error, you should be using <EditText> instead. EditText is a subclass of TextView, and some of the editing support is provided by TextView, so it's possible to set some input-related properties on a TextView. However, using a TextView along with input attributes is usually a cut & paste error. To input text you should be using <EditText>.
This check also checks subclasses of TextView, such as Button and CheckBox, since these have the same issue: they should not be used with editable attributes.
Issue id: TextViewEdits
结合以上说明,android:inputType的属性只对EditText有效,我认为EditText本身有抢夺焦点的作用,给TextView设置android:inputType的属性后可能也会导致焦点抢夺,导致点击“Text”文本并不会触发条目点击事件,而是被自身消耗掉了。
这里,要感谢下我的朋友margintop,他后来发现:如果已经设置了android:inputType的属性,再设置两个属性android:clickable和android:longClickable,这两个属性都设置成false,也可以达到预期的效果。也就是说android:inputType改变了那两个属性的默认值,把false改成了true。