如何在recyclerview内的所选项目后面显示自定义形状作为背景。我尝试了几件事,但都失败了:
activity_main.xml中:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/nav_drawer_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/drawer_background"
android:theme="@style/drawer"></android.support.v7.widget.RecyclerView>
</LinearLayout>
drawer_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/drawable_shape_selected" android:state_checked="true"></item>
<item android:drawable="@android:color/transparent"></item>
</selector>
drawable_shape_selected.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FFB74D"></solid>
</shape>
custom_layout.xml:对于RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical">
<TextView
android:id="@+id/TextViewDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello" />
</LinearLayout>
更新
itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
Toast.makeText(context, "Position " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
答案 0 :(得分:0)
像这样更改drawer_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/drawable_shape_selected"
android:state_pressed="true" />
<item android:drawable="@drawable/drawable_shape_selected"
android:state_focused="true" />
<item android:drawable="@android:color/transparent" />
</selector>
同时将android:focusableInTouchMode="true"
添加到custom_layout.xml
这是因为默认情况下,当触摸视图时,它将需要点击而不是焦点。如果您希望视图聚焦并在按下时更改其背景,请将其添加到您的视图中,即xml中的LinearLayout。
EDIT
:focusableInTouchMode
第一次禁用click时使视图触摸模式。首次使按钮单击发生时,在按钮和onFocuschange的java类中添加焦点侦听器添加{{ 1}}点击按钮。
view.performClick()