Start new Activity with onClick() in RecyclerView

后端 未结 10 783
渐次进展
渐次进展 2020-12-03 06:12

I want to go into a new Activity with the onClick() method but my code is not working. Can you please offer some advice. I have some issues with the recyclerView, since it\'

10条回答
  •  孤街浪徒
    2020-12-03 06:36

    Try this

    public class FragmentOne extends Fragment {
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            RecyclerView recyclerView = (RecyclerView) inflater.inflate(
                    R.layout.recycleview, container, false);
            ContentAdapter adapter = new ContentAdapter();
            recyclerView.setAdapter(adapter);
    
            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            return recyclerView;
        }
    
        public class ContentAdapter extends RecyclerView.Adapter implements View.OnClickListener {
            private static final int LENGTH = 50;
    
            public ContentAdapter() {
            }
    
            public class ViewHolder extends RecyclerView.ViewHolder {
    
                public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
                    super(inflater.inflate(R.layout.fragment_channel, parent, false));
                }
            }
    
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ChannelDetailActivity.class);
                startActivity(intent);
            }
    
            @Override
            public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    
                ViewHolder viewHolder = new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
                return viewHolder;
            }
    
            @Override
            public void onBindViewHolder(ViewHolder holder, int position) {
            }
    
            @Override
            public int getItemCount() {
                return LENGTH;
            }
        }
    }
    

    The adapter now implements the onclick and not the viewholder.

提交回复
热议问题