2015-01-15 179 views
0

我動態創建了以下RecyclerView。我想突出顯示單擊的項目,同時點擊它。點擊後,它會轉到下一個Activity。我已經給出瞭如下的背景XML:RecyclerView突出顯示項目點擊

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

有你爲什麼不在你ViewHolder類使用onClickListenner來處理單擊事件的原因?我昨天花了很多時間爲這種情況提出了最好的解決方案,對我來說這很容易。如果有什麼我不知道的請告訴我。 – Ced 2015-07-22 10:44:56

回答

0

您正在設置整個RecyclerView的背景(沒有被選中)。您需要設置行視圖的背景。在HistoryAdapter中的onCreateViewHolder中,您將充氣行視圖。 那個是需要有一個選擇器可繪製的背景(你可以在xml或代碼中設置它)。

0
hRecyclerView.setBackgroundResource(R.drawable.mylistview_background); 

首先刪除這一行,它是針對整個recyclerview。

您的自定義行/項目佈局應該像這樣(把mylistview_background.xml在繪製文件夾):

<RelativeLayout ... 
    android:background="@drawable/mylistview_background">... 
</RelativeLayout>