【发布时间】:2016-06-14 04:17:45
【问题描述】:
我有一个使用 Fragments 拆分视图屏幕的主详细信息应用程序。主屏幕是一个包含 RecyclerView 的列表。这是布局 XML。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Page Title" />
<android.support.v7.widget.RecyclerView
android:id="@+id/page_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
项目行布局xml如下。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:id="@+id/item_layout">
<TextView
android:id="@+id/contact_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<Button
android:id="@+id/message_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textSize="10sp"
/>
</LinearLayout>
在适配器类上,我创建了一个变量来保存所选项目的位置
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ListViewHolder> {
private int selectedPos;
@Override
public void onBindViewHolder(ListViewHolder holder, int position) {
holder.itemView.setSelected(selectedPos == position);
holder.bind(mData.get(position));
}
class ListViewHolder extends RecyclerView.ViewHolder {
public ListViewHolder(View itemView) {
super(itemView);
}
public void bind(ListEntity entity) {
//UI rendering
}
@OnClick(R.id.layout_campaign)
public void onItemClicked(View view) {
notifyItemChanged(selectedPos);
selectedPos = getLayoutPosition();
notifyItemChanged(selectedPos);
}
}
当我单击列表中的某个项目时,该列表项目未突出显示。看了很多关于这个问题的类似帖子,但无法让它工作。我错过了什么吗?
【问题讨论】:
标签: android android-recyclerview