2017-05-27 18 views
0

私はActivityRecyclerViewを持っています。各行にはButtonがあります。 どのように私は魔女のボタンをクリックして何かをすることができます。 手段:行#1「が」行番号2ボタンをクリックするAndroid RecyclerView子アイテムを取得

場合に「B」を示すボタン番組をクリック

場合。

答えて

0

これは一般的な問題であり、間違いなく多くの解決策があります。これは、最も汎用性のある私が見つけたものです:

この方法が機能する方法は、お使いのViewHolderオブジェクトでイベントを表示するには、リスナーとしてあなたのアダプターを登録することである:

ステップ1:
新しいを作成します。インタフェース・クラス:

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

ステップ2:
際トンリスナーにmotioneventおよびデータの位置を渡すためにあなたのViewHolderクラスを変更します彼は、ボタンが押された:

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 
    } 
} 

たら、押されたカードを知っている:)

関連する問題