在cardview中实现OnClickListener获取具体数据
Posted
技术标签:
【中文标题】在cardview中实现OnClickListener获取具体数据【英文标题】:Implements OnClickListener in cardview to get specific data 【发布时间】:2021-09-16 18:07:12 【问题描述】:使用我目前拥有的代码,当 Onclick 任何卡片视图 [图 2] 时,我可以检索每个出勤详细信息 [图 3]。
现在,我希望得到每个cardview中的具体数据。
流程:userlist.java [在此处实现 OnClickListener]-> userlist1.java
希望结果:
CardView 1 [info:test3] -> 1 出勤率 (MdkeONsLFaBK9DgyKMu)
CardView 2 [info:rea] -> 2 出勤 (Mdkf_TBTWI4D6yRyGLa) & (Mdkfbbtb2mRUZXEIwdr)
userlist.class
public class userlist extends AppCompatActivity
RecyclerView recyclerView;
DatabaseReference database, ab;
MyAdapter myAdapter;
ArrayList<Report> list;
String uid;
private FirebaseAuth auth;
private FirebaseUser user;
Menu menu;
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userlist);
user = auth.getInstance().getCurrentUser();
uid = user.getUid();
recyclerView = findViewById(R.id.userlist);
searchView = findViewById(R.id.action_search);
SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE);
String key = sharedPreferences.getString("key","");
String temp = sharedPreferences.getString("temp","");
database = FirebaseDatabase.getInstance().getReference("Class Information");
ab = database.child(uid).child("Student Attend");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
myAdapter = new MyAdapter(this, list);
recyclerView.setAdapter(myAdapter);
ab.addValueEventListener(new ValueEventListener()
@Override
public void onDataChange(@NonNull DataSnapshot snapshot)
for (DataSnapshot dataSnapshot : snapshot.getChildren())
Report report = dataSnapshot.getValue(Report.class);
list.add(report);
myAdapter.notifyDataSetChanged();
@Override
public void onCancelled(@NonNull DatabaseError databaseError)
);
@Override
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
@Override
public boolean onQueryTextSubmit(String query)
// filter recycler view when query submitted
myAdapter.getFilter().filter(query);
return false;
@Override
public boolean onQueryTextChange(String query)
// filter recycler view when text is changed
myAdapter.getFilter().filter(query);
return false;
);
return true;
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
switch (item.getItemId())
case R.id.menu_dateascending:
Collections.sort(list, Report.ReportDateOldestComparator);
Toast.makeText(userlist.this, "Sort by Date [Oldest - Latest]", Toast.LENGTH_SHORT).show();
myAdapter.notifyDataSetChanged();
return true;
case R.id.menu_descending:
Collections.sort(list, Report.ReportDateLatestComparator);
Toast.makeText(userlist.this, "Sort by Date [Latest - Oldest]", Toast.LENGTH_SHORT).show();
myAdapter.notifyDataSetChanged();
return true;
case R.id.action_search:
// Not implemented here
return false;
default:
break;
searchView.setOnQueryTextListener(queryTextListener);
return super.onOptionsItemSelected(item);
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>implements Filterable
Context context;
ArrayList<Report> list;
ArrayList<Report> listfilter;
SharedPreferences sharedpreferences;
public MyAdapter(Context context, ArrayList<Report> list)
this.context = context;
this.list = list;
this.listfilter = list;
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
return new MyViewHolder(v);
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position)
Report report = list.get(position);
holder.time.setText(report.getTime());
holder.duration.setText(report.getDuration());
holder.info.setText(report.getInfo());
@Override
public int getItemCount()
return list.size();
@Override
public Filter getFilter()
return new Filter()
@Override
protected FilterResults performFiltering(CharSequence charSequence)
String charString = charSequence.toString();
if (charString.isEmpty())
list = listfilter;
else
List<Report> filteredList = new ArrayList<>();
for (Report row : listfilter)
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getInfo().toLowerCase().contains(charString.toLowerCase()) || row.getTime().contains(charSequence))
filteredList.add(row);
list = (ArrayList<Report>) filteredList;
FilterResults filterResults = new FilterResults();
filterResults.values = list;
return filterResults;
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults)
list = (ArrayList<Report>) filterResults.values;
notifyDataSetChanged();
;
public class MyViewHolder extends RecyclerView.ViewHolder
TextView duration, time, info;
public View view;
String key, temp;
public MyViewHolder(@NonNull View itemView)
super(itemView);
time = itemView.findViewById(R.id.tvtemp);
duration = itemView.findViewById(R.id.tvfirstName);
info = itemView.findViewById(R.id.tvmatno);
SharedPreferences sharedPreferences = context.getSharedPreferences("myKey", Context.MODE_PRIVATE);
String key = sharedPreferences.getString("key","");
String temp = sharedPreferences.getString("temp","");
itemView.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View itemView)
sharedpreferences = context.getSharedPreferences("myKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("key", key);
editor.putString("temp", temp);
editor.apply();
Intent intent = new Intent(itemView.getContext(), userlist1.class);
itemView.getContext().startActivity(intent);// pass key to next activity;
Toast.makeText(itemView.getContext(), "Data retrieved from database", Toast.LENGTH_SHORT).show();
);
Report.java
public class Report
public String duration;
public String time;
public String info;
public Report()
public void setDuration(String duration)
this.duration = duration;
public void setTime(String time)
this.time = time;
public void setInfo(String info)
this.info = info;
public String getDuration()
return duration;
public String getTime()
return time;
public String getInfo()
return info;
public static Comparator<Report> ReportDateOldestComparator = new Comparator<Report>()
@Override
public int compare(Report o1, Report o2)
return o1.getTime().compareTo(o2.getTime());
;
public static Comparator<Report> ReportDateLatestComparator = new Comparator<Report>()
@Override
public int compare(Report o1, Report o2)
return o2.getTime().compareTo(o1.getTime());
;
userlist1.java
public class userlist1 extends AppCompatActivity
RecyclerView recyclerView;
DatabaseReference database,ab;
MyAdapter1 myAdapter1;
ArrayList<Report1> list;
String uid;
private FirebaseAuth auth;
private FirebaseUser user;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userlist1);
user = auth.getInstance().getCurrentUser();
uid = user.getUid();
recyclerView = findViewById(R.id.userlist1);
SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE);
String key = sharedPreferences.getString("key","");
String temp = sharedPreferences.getString("temp","");
String abc = sharedPreferences.getString("abc","");
database = FirebaseDatabase.getInstance().getReference("Class Information");
ab = database.child(uid).child("Student Attend");
//ab = database.child(uid).child("Student Attend").child(key).child("Attendance");
//ab = database.child(uid).child("Student Attend").child("test").child(key);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
//ArrayList<Report1> list = new ArrayList<Report1>();
myAdapter1 = new MyAdapter1(this,list);
recyclerView.setAdapter(myAdapter1);
ab.addListenerForSingleValueEvent(new ValueEventListener()
@Override
public void onDataChange(@NonNull DataSnapshot snapshot)
for (DataSnapshot childSnapshot : snapshot.getChildren())
/*List<Report1>list = new ArrayList<>();*/
for (DataSnapshot dataSnapshot : childSnapshot.child("Attendance").getChildren())
Report1 report1 = dataSnapshot.getValue(Report1.class);
list.add(report1);
myAdapter1.notifyDataSetChanged();
@Override
public void onCancelled(@NonNull DatabaseError databaseError)
throw databaseError.toException(); //
);
MyAdapter1.java
public class MyAdapter1 extends RecyclerView.Adapter<MyAdapter1.MyViewHolder>
Context context;
ArrayList<Report1> list;
public MyAdapter1(Context context, ArrayList<Report1> list)
this.context = context;
this.list = list;
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
View v = LayoutInflater.from(context).inflate(R.layout.item1,parent,false);
return new MyViewHolder(v);
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position)
Report1 report1 = list.get(position);
holder.matricno.setText(report1.getMatricno());
holder.password.setText(report1.getPassword());
holder.temp.setText(report1.getTemp());
public long getItemId(int position)
return position;
@Override
public int getItemViewType(int position)
return position;
@Override
public int getItemCount()
return list.size();
public class MyViewHolder extends RecyclerView.ViewHolder //public static class
TextView matricno, password, temp;
public View view;
public MyViewHolder(@NonNull View itemView)
super(itemView);
matricno = itemView.findViewById(R.id.tvmno);
password = itemView.findViewById(R.id.tvpassword);
temp = itemView.findViewById(R.id.tvtemperature);
itemView.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View itemView)
Toast.makeText(itemView.getContext(), "Data retrieved from database", Toast.LENGTH_SHORT).show();
);
Report1.java
public class Report1
public String matricno;
public String password;
public String temp;
public Report1()
public String getMatricno()
return matricno;
public String getPassword()
return password;
public String getTemp()
return temp;
public void setMatricno(String matricno)
this.matricno = matricno;
public void setPassword(String password)
this.password = password;
public void setTemp(String temp)
this.temp = temp;
【问题讨论】:
如果您遇到问题,最好在发布问题时创建MCVE。您为此问题发布了近 500(五百)行行代码。人们需要解析和尝试在线调试的内容很多。请编辑您的问题并隔离问题,这样可以增加获得帮助的机会。 【参考方案1】:新建一个Activity,获取Item的position
。通过Intent
传递数据。
holder.myItem.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View itemView)
Intent intent = new Intent(getApplicationContext(),ViewItemDetails.class);
intent.putExtra(“yourKey1”, value1);
intent.putExtra(“yourKey2”, value2);
startActivity(intent);
);
【讨论】:
以上是关于在cardview中实现OnClickListener获取具体数据的主要内容,如果未能解决你的问题,请参考以下文章
带圆角的 CardView 内的 ImageView 绘制不正确