我动态创建了以下RecyclerView
。我想点击它时突出显示点击的项目。点击后,它会转到下一个Activity
。我在下面给出了背景XML:
hRecyclerView.setBackgroundResource(R.drawable.mylistview_background);
这不是设定它的方法吗?我该怎么办?
hRecyclerView = (RecyclerView) findViewById(R.id.my_history_view);
// use a linear layout manager
hLayoutManager = new LinearLayoutManager(this);
hRecyclerView.setLayoutManager(hLayoutManager);
hRecyclerView.setVerticalScrollBarEnabled(false);
hRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
hRecyclerView.setBackgroundResource(R.drawable.mylistview_background);
hAdapter = new HistoryAdapter(history, this);
hRecyclerView.setAdapter(hAdapter);
hRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
// do whatever
if(position>0) {
History his = history.get(position - 1);
Intent intent = new Intent(getApplicationContext(), TrackActivity.class);
intent.putExtra("from", his.src_station);
intent.putExtra("to", his.dest_station);
intent.putExtra("train_no", his.train_no);
intent.putExtra("train_name", his.train_name);
startActivity(intent);
overridePendingTransition(R.anim.right_in, R.anim.left_out);
}
}
})
);
hRecyclerView.setItemAnimator(new DefaultItemAnimator());
mylistview_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<gradient android:endColor="#22000000" android:startColor="#a7a2288f" android:angle="270" />
</shape>
</item>
<item android:state_focused="true">
<shape>
<gradient android:endColor="#2200ff00" android:startColor="#a2008f00" android:angle="270" />
</shape>
</item>
</selector>
任何帮助都得到了很多赞赏!
答案 0 :(得分:0)
您正在设置整个RecyclerView的背景(不会被“选中”)。您需要设置行视图的背景。在HistoryAdapter中的onCreateViewHolder中,您将膨胀行视图。 THAT 是需要选择器drawable的背景(您可以在xml或代码中设置它。)
答案 1 :(得分:0)
hRecyclerView.setBackgroundResource(R.drawable.mylistview_background);
首先删除这一行,它是整个回收者视图。
您的自定义行/项布局应如下所示(将mylistview_background.xml放在drawable文件夹中):
<RelativeLayout ...
android:background="@drawable/mylistview_background">...
</RelativeLayout>