RecyclerViewAdapter位于片段中。我能够在片段中调用OnItemClickListener,但问题是我在Ativity中需要它

我试图再次调用接口,但没有结果(空)

  public class SongsFragment extends Fragment implements ARecyclerViewAdapter.OnItemClickListener
{
    OnHeadlineSelectedListener callback;

    @Override
    public void onItemClick(int position)
    {
        // TODO: Implement this method
        String TAG = "AAA";
        Log.e(TAG, "lol" + position);
    }

    View v;
    private RecyclerView myrecyclerView;
    private List<AudioModel> listSong;

    DatabaseHelper myDB;

    public SongsFragment() {

    }

    public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener callback) {
        this.callback = callback;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // TODO: Implement this method
        v = inflater.inflate(R.layout.songs_fragment, container, false);

        myrecyclerView = (RecyclerView) v.findViewById(R.id.audio_recyclerview);
        ARecyclerViewAdapter adapter = new ARecyclerViewAdapter(getContext(),listSong);
        adapter.setOnItemClickListener(this);
        myrecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myrecyclerView.setAdapter(adapter);
        return v;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        // TODO: Implement this method
        super.onCreate(savedInstanceState);

        DatabaseHelper myDB = new DatabaseHelper(getActivity());
        listSong = new ArrayList<>();
        listSong.addAll(myDB.getAllSongs());

    }

    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }
}

最佳答案

在活动和片段之间创建接口。创建界面使您的片段可重复使用,并易于将其放入其他活动中。

在活动片段上添加侦听器,以侦听来自recyclerview的任何单击。下面的例子:

class SongsFragment {

  interface RecyclerViewClickListener {
    void onClick(int position); // you can pass any parameters here you need from recyclerview to activity
  }

  private RecyclerViewClickListener mListener;

  // set the listener here from activity
  public void setListener(RecyclerViewClickListener listener) {
    mListener = listener;
  }

  @Override
  public void onItemClick(int position) {
    // TODO: Implement this method
    String TAG = "AAA";
    Log.e(TAG, "lol" + position);
    mListener.onClick(position);
  }
}


活动:

class YourActivity extends AppCompatActivity {
  // some codes
  private void setupFragment() {
    SongsFragment fragment = new SongsFragment();
    fragment.setListener(new RecyclerViewClickListener() {
      @Override
      void onClick(int position) {
        // do something on the object clicked from rv
      }
    });
  }
}

关于java - 如何将Recyclerview的OnClickListener放入Activity,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56800568/

10-10 04:11