如何将onClickListener()添加到onBindViewHolder?

时间:2018-04-09 02:17:58

标签: android android-recyclerview onclick onclicklistener

我正在使用Firebase创建搜索栏,一切正常,但我不知道如何设置点击侦听器RecyclerView。点击结果时,我需要显示更多信息。我希望你能帮助我。这是我的主要代码和我的SearchAdapter

主要代码:

public class SearchCousesActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

private GoogleApiClient googleApiClient;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef, myRef2, databaseReference;
private String userID;
private StorageReference mStorageRef;
FirebaseUser firebaseUser;

EditText SearchCoursesETXT;
RecyclerView recyclerView;

ArrayList<String> titleList;
ArrayList<String> lugarList;
ArrayList<String> costoList;
ArrayList<String> duracionList;
ArrayList<String> aprobacionList;
ArrayList<String> URLimagenList;

SearchAdapter searchAdapter;

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

    SearchCoursesETXT = (EditText) findViewById(R.id.EditTXTSearchCour);
    recyclerView = (RecyclerView) findViewById(R.id.RVResultsCourses);



    ///////////////////////////////////////////////////////////////////////////////////////////
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    googleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    firebaseAuth = FirebaseAuth.getInstance();
    firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null){
                // setUserData(user);
            } else {
                goLogIn();
            }

        }
    };
    ///////////////////////////////////////////////////////////////////////////////////////////



    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference("Courses");
    FirebaseUser user = firebaseAuth.getCurrentUser();


    databaseReference = FirebaseDatabase.getInstance().getReference();

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));

    titleList = new ArrayList<>();
    lugarList = new ArrayList<>();
    costoList = new ArrayList<>();
    aprobacionList = new ArrayList<>();
    duracionList = new ArrayList<>();
    URLimagenList = new ArrayList<>();


    SearchCoursesETXT.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!s.toString().isEmpty()){
                setAdapter(s.toString());
            }else {
                titleList.clear();
                lugarList.clear();
                costoList.clear();
                duracionList.clear();
                aprobacionList.clear();
                URLimagenList.clear();
                recyclerView.removeAllViews();
            }

        }
    });

}

private void setAdapter(final String searchedString) {



    databaseReference.child("Courses").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            titleList.clear();
            lugarList.clear();
            costoList.clear();
            duracionList.clear();
            aprobacionList.clear();
            URLimagenList.clear();
            recyclerView.removeAllViews();

            int counter = 0;

            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                String uid = snapshot.getKey();
                String title = snapshot.child("title").getValue(String.class);
                String place = snapshot.child("state").getValue(String.class);
                String costo = snapshot.child("costo").getValue(String.class);
                String duracion = snapshot.child("duracion").getValue(String.class);
                String aprobacion = snapshot.child("status").getValue(String.class);
                String URLimg = snapshot.child("uri").getValue(String.class);

                if (title.toLowerCase().contains(searchedString.toLowerCase())){
                    titleList.add(title);
                    lugarList.add(place);
                    costoList.add(costo);
                    duracionList.add(duracion);
                    aprobacionList.add(aprobacion);
                    URLimagenList.add(URLimg);

                    counter++;
                }
                if (counter == 20)
                    break;
            }

            searchAdapter = new SearchAdapter(SearchCousesActivity.this, titleList, lugarList, costoList, duracionList, aprobacionList, URLimagenList);
            recyclerView.setAdapter(searchAdapter);


        }


        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

@Override
protected void onStart() {
    super.onStart();
    firebaseAuth.addAuthStateListener(firebaseAuthListener);


}

private void goLogIn() {
    Intent intent = new Intent(this, LoginActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

这是我的SearchAdapter:

public class SearchAdapter extends RecyclerView.Adapter <SearchAdapter.SearchViewHolder> {

String[] mDataset = { "Data", "In", "Adapter" };

Context context;
ArrayList<String> titleList;
ArrayList<String> lugarList;
ArrayList<String> costoList;
ArrayList<String> duracionList;
ArrayList<String> aprobacionList;
ArrayList<String> URLimagenList;






class SearchViewHolder extends RecyclerView.ViewHolder{


    ImageView course_Image;
    TextView course_Title, course_Place, course_Cost;

    public SearchViewHolder(View itemView) {
        super(itemView);


        course_Image = (ImageView) itemView.findViewById(R.id.courseImage);
        course_Title = (TextView) itemView.findViewById(R.id.courseTitle);
        course_Place = (TextView) itemView.findViewById(R.id.coursePlace);
        course_Cost = (TextView) itemView.findViewById(R.id.courseCosto);
    }
}


public SearchAdapter(Context context, ArrayList<String> titleList, ArrayList<String> lugarList, ArrayList<String> costoList, ArrayList<String> duracionList, ArrayList<String> aprobacionList, ArrayList<String> URLimagenList) {
    this.context = context;
    this.titleList = titleList;
    this.lugarList = lugarList;
    this.costoList = costoList;
    this.duracionList = duracionList;
    this.aprobacionList = aprobacionList;
    this.URLimagenList = URLimagenList;
}

@Override
public SearchAdapter.SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.search_list_items,parent, false);
    return new SearchAdapter.SearchViewHolder(view);
}



@Override
public void onBindViewHolder(SearchViewHolder holder, int position) {
    holder.course_Title.setText(titleList.get(position));
    holder.course_Place.setText(lugarList.get(position));
    holder.course_Cost.setText(costoList.get(position));
    Glide.with(context).load(URLimagenList.get(position)).asBitmap().placeholder(R.mipmap.ic_launcher).into(holder.course_Image);



}

2 个答案:

答案 0 :(得分:1)

不要在BindViewHolder中制作点击监听器,而不是在Adapter的ViewHolder中制作clicklistener。

class SearchViewHolder extends RecyclerView.ViewHolder{
        ImageView course_Image;
        TextView course_Title, course_Place, course_Cost;

        public SearchViewHolder(View itemView) {
            super(itemView);


            course_Image = (ImageView) itemView.findViewById(R.id.courseImage);
            course_Title = (TextView) itemView.findViewById(R.id.courseTitle);
            course_Place = (TextView) itemView.findViewById(R.id.coursePlace);
            course_Cost = (TextView) itemView.findViewById(R.id.courseCosto);
itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Your logic

        }
    });
  }
}

答案 1 :(得分:0)

试试这个

holder.showResultView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Your logic
        }
    });