如何在recyclerview上添加SetOnClicklistener

时间:2018-09-19 09:11:13

标签: java android android-recyclerview onclicklistener

这是我的适配器。

     package com.lim.fiture.fiture.adapters;

    import android.content.Context;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.EditText;

    import com.lim.fiture.fiture.R;
    import com.lim.fiture.fiture.models.Exercise;

    import java.util.ArrayList;

    public class AdminActivityAdapter extends RecyclerView.Adapter <AdminActivityAdapter.ViewHolder>{

        Context context;
        public ArrayList <Exercise> exercises;


        private OnItemClicked onClick;

        //make interface like this
        public interface OnItemClicked {
            void onItemClick(int position);
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_admin_adapter,parent,false);
            AdminActivityAdapter.ViewHolder viewHolder = new AdminActivityAdapter.ViewHolder(view);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
        holder.exerciseName.setText(exercises.get(position).getExerciseName());
        holder.mainMuscleGroup.setText(exercises.get(position).getMainMuscleGroup());
        holder.otherMuscleGroup.setText(exercises.get(position).getOtherMuscleGroup());
        holder.type.setText(exercises.get(position).getType());
        holder.equipment.setText(exercises.get(position).getEquipment());
        holder.difficulty.setText(exercises.get(position).getDifficulty());
         holder.deleteExercise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClick.onItemClick(position);
            }
        });

    }




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







           public class ViewHolder extends RecyclerView.ViewHolder {
        private EditText exerciseName, mainMuscleGroup, otherMuscleGroup, type, equipment, difficulty;
        private ImageButton deleteExercise;
        public ViewHolder(View itemView) {
            super(itemView);

            exerciseName = itemView.findViewById(R.id.exerciseName);
            mainMuscleGroup = itemView.findViewById(R.id.mainMuscleGroup);
            otherMuscleGroup = itemView.findViewById(R.id.otherMuscleGroup);
            type = itemView.findViewById(R.id.type);
            equipment = itemView.findViewById(R.id.equipment);
            difficulty = itemView.findViewById(R.id.difficulty);
            deleteExercise = itemView.findViewById(R.id.deleteBtn);




        }
    }
}

这是我的活动

     package com.lim.fiture.fiture.activities;

import android.content.ClipData;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.lim.fiture.fiture.R;
import com.lim.fiture.fiture.adapters.AdminActivityAdapter;
import com.lim.fiture.fiture.adapters.ExercisesAdapter;
import com.lim.fiture.fiture.models.Exercise;

import java.util.ArrayList;



public class AdminActivity extends AppCompatActivity implements AdminActivityAdapter.OnItemClicked {

    private RecyclerView exercisesList;
    private AdminActivityAdapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private FloatingActionButton addExerciseBtn;
    private ExercisesAdapter exercisesAdapter;
    private ArrayList<Exercise> exercises = new ArrayList<>();

    //TODO: instance variables for firebase database
    private DatabaseReference exerciseReference;
    private static final String TAG = "AdminActivity";
    private FirebaseAuth mAuth;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);

        mAuth = FirebaseAuth.getInstance();
        exerciseReference = FirebaseDatabase.getInstance().getReference("Exercises");
        findViews();
        loadExercises();




    }


    @Override
    protected void onStart() {
        super.onStart();
        FirebaseUser user = mAuth.getCurrentUser();
        if (user != null) {
            // do your stuff
        } else {
            signInAnonymously();
        }
    }



    private void signInAnonymously() {
        mAuth.signInAnonymously().addOnSuccessListener(this, new OnSuccessListener<AuthResult>() {
            @Override
            public void onSuccess(AuthResult authResult) {
                // do your stuff
            }
        })
                .addOnFailureListener(this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        Log.e(TAG, "signInAnonymously:FAILURE", exception);
                    }
                });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.addExerciseBtn:
                startActivity(new Intent(this, AddExerciseStepOne.class));
                break;
        }
    }


    public void findViews() {
        addExerciseBtn = findViewById(R.id.addExerciseBtn);
        addExerciseBtn.setOnClickListener(this);
        exercisesList = findViewById(R.id.exercisesList);
        layoutManager = new LinearLayoutManager(this);
        exercisesList.setLayoutManager(layoutManager);

        ActionBar bar = getSupportActionBar();
        bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2980b9")));
        bar.setTitle("Fiture Admin");


    }



    public void loadExercises() {
        exerciseReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Exercise exercise = dataSnapshot.getValue(Exercise.class);
                Log.d(TAG, exercise.toString());
                exercises.add(exercise);
                exercisesAdapter = new ExercisesAdapter(AdminActivity.this, exercises);
                exercisesList.setAdapter(exercisesAdapter);

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }

        });
    }


    @Override
    public void onItemClick(int position) {

    }
}

所以我想做的是,当单击deletebutton时,它将在回收器视图中删除选定的(这是一个包含有关练习的详细信息的cardview),并在firebase中将其删除,但是我很难在上面找到教程互联网。有人知道该怎么做吗?急需您的帮助。谢谢

3 个答案:

答案 0 :(得分:5)

public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewHolder> {// Recyclerview will extend to

private List<FileName> fileNames;

  private Context context;

//declare interface 
 private OnItemClicked onClick;

//make interface like this
    public interface OnItemClicked {
        void onItemClick(int position);
    }

  public RecycleViewAdapter(Context context,List<FileName> fileNames) {
    this.context = context;
    this.fileNames = fileNames;
}

现在将点击分配给界面

@Override
    public void onBindViewHolder(RecycleViewHolder holder, final int position) {
        //............//
        holder.title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClick.onItemClick(position);
            }
        });

您的活动

公共类MainActivity扩展Activity实现OnItemClicked {

private RecyclerView mRecyclerView;
private RecycleViewAdapter mAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_city);

    mRecyclerView = (RecyclerView)findViewById(R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    mAdapter = new RecycleViewAdapter(cities, R.layout.row_city, this);
    mRecyclerView.setAdapter(mAdapter);

    mAdapter.setOnClick(MainActivity.this); // Bind the listener
}

@Override
public void onItemClick(int position) {
    // The onClick implementation of the RecyclerView item click
//ur intent code here

}

答案 1 :(得分:1)

您可以尝试

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 imageList.get(position); // here you will get the clicked item from 
    //your imagelist and you can check by getting a title  by using this

    String title= imageList.get(position).getTitle();

           } 
        });

答案 2 :(得分:0)

我建议使用Epoxy和Kotlin-它有助于更​​轻松地解决此问题(但这只是恕我直言)

您的情况可以是:

在活动(或片段)中创建界面

interface ExecriseClickListener {
    public void onExerciseClick(Exercise exercise);
}

在适配器内部创建字段

ExecriseClickListener listener;

在ViewHolder中添加逻辑

public void onBindViewHolder(ViewHolder holder, int position) {
...
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            listener.onExerciseClick(exercises.get(position));
        }
    });

并从活动(或片段)中设置监听器

exercisesAdapter.listener = new ExecriseClickListener{
@Override
        public void onExerciseClick(Exercise exercise) {
            //TODO
        }
    });

How to inflate different layout using same recycle adapter?

我的字符串建议-尝试使用环氧树脂。它允许您以更少的代码使用列表中的许多不同项目。 epoxy on github