2017-05-27 93 views
0

我有一個RecyclerView在我的Activity。每行有一個Button。 我怎樣才能讓女巫按鈕點擊並做點什麼。 指:Android RecyclerView獲取子項

如果行#1上按鈕顯示的 「a」

如果行#2點擊按鈕示出 「B」 被點擊;

回答

0

這是一個常見問題,毫無疑問有很多解決方案。這是我發現的一個是最通用的:

這種方法的工作方式是通過註冊您的適配器作爲一名聽衆在ViewHolder對象查看事件:

第1步:
創建一個新的接口類:

public interface MyCardListener { 
    boolean buttonPressed(View v, MotionEvent motionEvent, int position); 
} 

步驟2:
修改您ViewHolder類噸時的motionevent和數據位置傳遞給聽者他按下按鈕:

public class MyCardViewHolder extends RecyclerView.ViewHolder { 

    private Button actionBtn; 

    public MyCardViewHolder(View itemView) {...} 

    public void setListener(final MyCardListener listener, final int position){ 
     actionBtn.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View view, MotionEvent motionEvent){ 
       return listener.buttonPressed(view, motionEvent, position); 
      } 
     }); 
    } 
} 

第3步:
修改您Adapter接收按鈕事件:

public class MyCardAdapter extends RecyclerView.Adapter<MyCardViewHolder> implements MyCardListener { 

    ... 

    @Override 
    public void onBindViewHolder(MyCardViewHolder holder, int position){ 
     ... 
     holder.setListener(this, position) 
    } 

    @Override 
    public boolean buttonPressed(View v, MotionEvent motionEvent, int pos){ 
     //the button on the card at position pos was pressed 
    } 
} 

一旦你的位置,你就知道這是壓卡:)

相關問題