Home > Software engineering >  RecylerView onClickListener works on all fragment
RecylerView onClickListener works on all fragment

Time:11-26

I have implemented a recyclerview in my activity and I added a onclick listener to recently. It was working fine, until I switch over to another fragment and realized the click was also working there so if I pressed randomly somewhere on the screen it would bring me the item click in the recycler view. Please let me know how can I only make the recyclerview be clickable on one activity, the home page and no the other.

HomePage.class

package com.example.movieapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.navigation.NavigationBarView;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;

public class HomePage extends AppCompatActivity implements NavigationBarView.OnItemSelectedListener {
    private DrawerLayout drawer;

    RecyclerView recylerView;
    MovieAdapter mainAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        recylerView = (RecyclerView) findViewById(R.id.rv);
        recylerView.setLayoutManager(new LinearLayoutManager(this));

        FirebaseRecyclerOptions<Model> options =
                new FirebaseRecyclerOptions.Builder<Model>()
                        .setQuery(FirebaseDatabase.getInstance().getReference().child("movie"), Model.class)
                        .build();

        mainAdapter = new MovieAdapter(options);
        recylerView.setAdapter(mainAdapter);

        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this::onNavigationItemSelected);


        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        getSupportActionBar().setTitle(null);
        toggle.setDrawerIndicatorEnabled(true);


        toggle.syncState();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }



    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId()) {
            case R.id.nav_home:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new HomeFragment()).commit();
                break;
            case R.id.nav_profile:
               // Intent intent = new Intent (getApplicationContext(), UserProfile.class);
               // startActivity(intent);
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new ProfileFragment()).commit();
                break;
            case R.id.nav_cart:

                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new CartFragment()).commit();
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }




    @Override
    public void onStart() {
        super.onStart();
        mainAdapter.startListening();
    }

    @Override
    public void onStop() {
        super.onStop();
        mainAdapter.stopListening();
    }
}


MovieAdapter.class

public class MovieAdapter extends FirebaseRecyclerAdapter<Model,MovieAdapter.myViewHolder> {




    /**
     * Initialize a {@link RecyclerView.Adapter} that listens to a Firebase query. See
     * {@link FirebaseRecyclerOptions} for configuration options.
     *
     * @param options
     */
    public MovieAdapter(@NonNull FirebaseRecyclerOptions<Model> options) {
        super(options);
    }

    @Override
    protected void onBindViewHolder(@NonNull myViewHolder myViewHolder, int i, @NonNull Model model) {
        myViewHolder.name.setText(model.getName());
        myViewHolder.shortDesc.setText(model.getShortDesc());
        myViewHolder.release.setText(model.getRelease());

        Glide.with(myViewHolder.img.getContext()).load(model.getImage()).placeholder(R.drawable.common_google_signin_btn_icon_dark)
                .error(R.drawable.common_google_signin_btn_icon_dark_normal)
                .into(myViewHolder.img);


        myViewHolder.itemView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent intent = new Intent (view.getContext(), MovieDetails.class);
                Bundle bundle = new Bundle();

                String test =  model.getName()   " Selected";

                Toast toast = Toast.makeText(view.getContext(), test ,Toast.LENGTH_SHORT);
                toast.show();

                view.getContext().startActivity(intent);
            }
        });
    }

    @NonNull
    @Override
    public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_item, parent, false);
        return new myViewHolder(view);
    }

    class myViewHolder extends RecyclerView.ViewHolder {

        ImageView img;
        TextView name,shortDesc,release;

        public myViewHolder(@NonNull View itemView) {
            super(itemView);

            img = (ImageView) itemView.findViewById(R.id.img1);
            name = (TextView) itemView.findViewById(R.id.nametext);
            shortDesc = (TextView) itemView.findViewById(R.id.shortDesctext);
            release = (TextView) itemView.findViewById(R.id.releasetext);
        }
    }
}

CodePudding user response:

It works in every time you used this adapter because the onclicklistener is always working, to change this you can create your own custom listener interface, so you can control to add it or not

public interface OnModelClickListener {
    void onClick(Model model);
}

You need to create the instance in the adapter and setter for it

private OnModelClickListener onModelClickListener

public void setOnModelClickListener(OnModelClickListener listener) (
    this.onModelClickListener = listener;
}

and inside onBindViewHolder you will run this listener if it is not null

@Override
protected void onBindViewHolder(@NonNull myViewHolder myViewHolder, int i, @NonNull Model model) {
    myViewHolder.name.setText(model.getName());
    myViewHolder.shortDesc.setText(model.getShortDesc());
    myViewHolder.release.setText(model.getRelease());

    Glide.with(myViewHolder.img.getContext()).load(model.getImage()).placeholder(R.drawable.common_google_signin_btn_icon_dark)
                .error(R.drawable.common_google_signin_btn_icon_dark_normal)
                .into(myViewHolder.img);

    if (onModelClickListener != null) {
        myViewHolder.itemView.setOnClickListener(v -> {
            onModelClickListener.onClick(model)
        });
    }
}

In fragment that you want the listener to work on it, you will use the setter

adapter.setOnModelClickListener(model -> {
    Intent intent = new Intent (view.getContext(), MovieDetails.class);
    Bundle bundle = new Bundle();

    String test =  model.getName()   " Selected";

    Toast toast = Toast.makeText(view.getContext(), test ,Toast.LENGTH_SHORT);
    toast.show();

    startActivity(intent);
});
``
  • Related