Cannot open fragment when click on itemView on holder

I trying to use fragment instead of activity as much as possible, in my custom adapter PostAdapter I use holder.itemView.setOnClickListener method to pass and open DetailsFragment at the end, but when I click on any item on recyclerView it's not doing anything

here's the PostAdapter Class

    public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
    private Context context;
    private List<Item> items;

    public PostAdapter(Context context, List<Item> items) {
        this.context = context;
        this.items = items;
    }

    @NonNull
    @Override
    public PostAdapter.PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.post_item, parent, false);
        return new PostViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        final Item item = items.get(position);
        holder.postTitle.setText(item.getTitle());
        final Document document = Jsoup.parse(item.getContent());
        Elements elements = document.select("img");

//        Log.d("CODE", "Image: "+elements.get(0).attr("src"));
//        Log.d("Text",document.text());
        holder.postDescription.setText(document.text());
        Glide.with(context).load(elements.get(0)
                .attr("src"))
                .into(holder.postImage);

        holder.itemView.setOnClickListener(view -> {
            DetailsFragment detailsFragment = new DetailsFragment();

            Bundle bundle = new Bundle();

            bundle.putString("url", item.getUrl());
            bundle.putString("itemTitle", item.getTitle());
            bundle.putString("title", item.getTitle());
            bundle.putString("content", item.getContent());
            int youtubeThumbnailImagesetVisibility = 0;

            Element element = document.body();

            String youtubeThumbnailImageSrc = "";
            String youTubeLink = "";
            for (Element e : element.getElementsByClass
                    ("YOUTUBE-iframe-video")) {
                youtubeThumbnailImageSrc = e.attr("data-thumbnail-src");
                youTubeLink = e.attr("src");
                Log.e("YouTube thumbnail", youtubeThumbnailImageSrc);
                Log.e("Youtube link", youTubeLink);
            }

            if (youtubeThumbnailImageSrc.isEmpty()) {
                youtubeThumbnailImagesetVisibility = 8;
                bundle.putInt("youtubeThumbnailImageSetVisibility",
                        youtubeThumbnailImagesetVisibility);
            } else {
                bundle.putString("youtubeThumbnailImageSrc", youtubeThumbnailImageSrc);
                bundle.putString("youTubeLink", youTubeLink);
            }

//             String imageSrc = elements.get(0).attr("src");
//             bundle.putString("blogImage",imageSrc);

            detailsFragment.setArguments(bundle);

            FragmentManager fragmentManager = ((Activity)context).getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.nav_view,detailsFragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
        });

    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public class PostViewHolder extends RecyclerView.ViewHolder {

        ImageView postImage;
        TextView postTitle;
        TextView postDescription;

        public PostViewHolder(View itemView) {
            super(itemView);
            postImage = (ImageView) itemView.findViewById(R.id.postImage);
            postTitle = (TextView) itemView.findViewById(R.id.postTitle);
            postDescription = (TextView) itemView.findViewById(R.id.postDescription);

        }
    }
}

DetailsActivity Fragment

    public class DetailsFragment extends android.app.Fragment {

    private TextView titleTextView, contentTextView;
    //   private ImageView blogImage;
    private PicassoImageGetter imageGetter;
    private ImageView youtubeThumbnailImage;
    private FloatingActionButton fab;
    private ScrollView scrollView;
    private SpinKitView spinKitView;
    private Button visitSite;
    private View view;
    private String url,title,content, youtubeThumbnailImageSrc, youTubeLink,sharingContent;
    private int youtubeThumbnailImageSetVisibility;

    public DetailsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_details, container, false);
                spinKitView = (SpinKitView) view.findViewById(R.id.spin_kit);
        scrollView = (ScrollView) view.findViewById(R.id.scrollView);
        titleTextView = (TextView) view.findViewById(R.id.titleTextView);
        contentTextView = (TextView)view.findViewById(R.id.blogContent);
        fab = (FloatingActionButton) view.findViewById(R.id.fab);
        youtubeThumbnailImage = (ImageView) view.findViewById(R.id.youtubeThumbnailImage);
        visitSite = (Button) view.findViewById(R.id.visitSite);

        if(getArguments() != null){
            Bundle bundle = getArguments();
            url = bundle.getString("url");
            title = bundle.getString("itemTitle");
            content = bundle.getString("content");
            youtubeThumbnailImageSrc = bundle.getString("youtubeThumbnailImageSrc");
            youTubeLink = bundle.getString("youTubeLink");
            youtubeThumbnailImageSetVisibility = bundle.getInt("youtubeThumbnailImageSetVisibility");

        }

//        blogImage = (ImageView) findViewById(R.id.blogImage);

        spinKitView.setVisibility(View.VISIBLE);

        titleTextView.setText(title);
        contentTextView.setMovementMethod(LinkMovementMethod.getInstance());


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            scrollView.setOnScrollChangeListener((v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
                //   Log.d("ScrollView","scrollX_"+scrollX+"_scrollY_"+scrollY+"_oldScrollX_"+oldScrollX+"_oldScrollY_"+oldScrollY);
                if (scrollY > 0 && fab.isShown()) {
                    fab.hide();
                } else if (scrollY < 22) {
                    fab.show();

                }
            });
        } else {
            scrollView.getViewTreeObserver().addOnScrollChangedListener(() -> {
                int mScrollY = scrollView.getScrollY();
                if (mScrollY > 0 && fab.isShown()) {
                    fab.hide();
                } else if (mScrollY < 22) {
                    fab.show();
                }
            });
        }

        fab.setOnClickListener(view -> {
            sharingContent = "\n" + url;
            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            sharingIntent.putExtra(Intent.EXTRA_TEXT,sharingContent);
            sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(Intent.createChooser(sharingIntent, "Share via"));
        });

        //       String imageSrc = getIntent().getStringExtra("blogImage");
        //       Glide.with(getApplicationContext()).load(imageSrc).into(blogImage);

      youtubeThumbnailImage.setVisibility(youtubeThumbnailImageSetVisibility);
        youtubeThumbnailImage.setAdjustViewBounds(true);
        Picasso.get().load(youtubeThumbnailImageSrc).into(youtubeThumbnailImage);

        youtubeThumbnailImage.setOnClickListener(view -> {
            Intent youTube = new Intent
                    (Intent.ACTION_VIEW, Uri.parse(youTubeLink));
            startActivity(youTube);
        });

        imageGetter = new PicassoImageGetter(contentTextView, getActivity());
        Spannable html;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            html = (Spannable) Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY, imageGetter, null);
        } else {
            html = (Spannable) Html.fromHtml(content, imageGetter, null);
        }

        contentTextView.setText(html);
        spinKitView.setVisibility(View.GONE);

        visitSite.setOnClickListener(view -> {
            Bundle bundle = new Bundle();
            bundle.putString("url", url );

            VisitSiteFragment visitSiteFragment = new VisitSiteFragment();
            visitSiteFragment.setArguments(bundle);

            FragmentManager manager = getFragmentManager();
            FragmentTransaction fragmentTransaction = manager.beginTransaction();

            fragmentTransaction.replace(R.id.detailsFragment,visitSiteFragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
        });
        return view;
    }

}

I tried to use android.support.v4.app and replace this line

FragmentManager fragmentManager = ((Activity)context).getFragmentManager();

with this

FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();

as described in this answer but this did not working also

Call fragment on activity class

Fragments should attach to activities. Make an interface implement it in your activity then initial the interface in your adapter. Call the method in clickListener then you can do anything in activity inside the proper method that is invoked by click.

holder.nameImage.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

       yourInterface.OnItemclick();

    }
});

Make sure to initialize it.

Set a click listener to a RecyclerView, You can't just use a lambda to get the same result. We'll see it in a Android is Kotlin first. I recommend you to join my free masterclass so that you can easily start with it. override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = items[position] holder.bind(item) holder.itemView.setOnClickListener� The problem is that toolbar is just another widget on your Activity and cannot be shared between multiple activities. So you should add toolbar view to the layout of the Activity which you are starting (ArticleActivity). As another option you can show Fragment over RecyclerView instead of starting new Activity.

Inside the onBindViewHolder you have to implement it like this :

holder.nameImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             ...
            //Toast.makeText(mContext,position+  " pozicioni",Toast.LENGTH_LONG).show();
        }
    });

Where you have to replace the "nameImage".

Android Fragments Tutorial: An Introduction with Kotlin , This is also sometimes called Adding a Fragment Statically. To do this, open activity_main.xml, select the Text tab and add the following inside of� i am using a recyclerView to show my listitems in the navigation drawer.I have implemented the onclickListener but i have been stuck on how to open a different activity when items are clicked. All my items do on item click as of now as per the code is to display a toast with the item position. I would appreciate the help. AdapterClass.java

Solved

The cause of the problem in this line

fragmentTransaction.replace(R.id.nav_view,detailsFragment);

I tried to replace the navigation drawer view, but I'm supposed to put the view that contains the recyclerView

fragmentTransaction.replace(R.id.parentLayout,detailsFragment);

Your ViewHolders Could Be Doing So Much More, I can't decide if it is a holdover from ListView, or just a paradigm that people ViewHolders that do absolutely nothing other than hold references to some views . Let's start with a dumb ViewHolder and an Adapter that has too much work to do. view in the ViewHolder, then handle the click events on two separate views . So instead of doing m vai did you can pass the context of the fragment when you first initialize your adapter. So in your constructor for your adapter you can add an argument like this // variable to hold fragment private Fragment fragment; public MyCustomAdapter(Fragment fragment) { this.fragment = fragment; }

Defining item click listener for RecyclerView in Android, Android RecyclerView doesn't come with the Item Click Listener that you Here is an example of how to implement the view holder item clicker listener The actual implementation of the onclick event will be from an activity or fragment findViewById(R.id.city_name);. itemView.setOnClickListener( this ); // bind the listener. yes we can set click listener in ViewHolder, but I need pass back the clicked item view and position to my fragment for further process – Xcihnegn Feb 3 '15 at 11:03 add a comment | 1

Using the RecyclerView, OnItemClickListener interface for binding to the click events for individual items ViewHolder { // Your holder should contain a member variable // for any view that each subview public ViewHolder(View itemView) { // Stores the itemView in a an existing list) and it cannot be easily determined whether each row changed. I like to add a OnItemClickListener interface in Adapter with an onClick method invoked when you click on the item view from the ViewHolder. Thus the responsibility of managing the click on an item is outside the ViewHolder and Adapter. Will the activity or fragment which will decide what to do. Add an interface to the listener and the listener

Which is the best approach for implementing RecyclerView item click?, I usually go with option 1 (add it to the ViewHolder), then propagate the click event to the Fragment/Activity via a Bus mechanism. this is my fragment where data is first loaded and my recycler adapter is as `private void SetupRecyClerView() {myRecyclerView.SetLayoutManager(new Android.Support.V7.Widget.LinearLayoutManager(myRecyclerView.Context));

Comments
  • The problem is you want to add the fragment to non-activity class. Make an interface for listening on click listener and then in the activity you can replace or add the fragment.
  • replace "nameImage" with What? , If you mean "postImage" I don't need on click to implement on Image click, the view is consists of postImage, postTitle, postDescription, all views consider "itemView" and the problem not in this part!
  • so you want to open the fragment by clicking? @MarkDeSpain
  • on clicking in any itemView on the recyclerView, this was working when I used Intent and activity, after I convert the DetailsActivity to fragment the problem appeared