我正在開發一個Android應用程序,我在其中使用RecyclerView
。假設我的RecyclerView
中有6個項目,即[A, B, C, D, E, F]
。那麼我怎樣才能獲得這些項目的點擊次數呢?計算一個RecyclerView項目上的點擊次數
例如:
如果用戶打開項目B
4倍。我怎樣才能得到count = 4
?
P.s. count
只應在用戶點擊相同項目時增加。
我正在開發一個Android應用程序,我在其中使用RecyclerView
。假設我的RecyclerView
中有6個項目,即[A, B, C, D, E, F]
。那麼我怎樣才能獲得這些項目的點擊次數呢?計算一個RecyclerView項目上的點擊次數
例如:
如果用戶打開項目B
4倍。我怎樣才能得到count = 4
?
P.s. count
只應在用戶點擊相同項目時增加。
在支架
itemView.setOnClickListener(){
onClick(){
// count up
}
}
每個項目也需要一個id
知道,它是項目
您可以在適配器中創建一個Map<Integer, Integer> clicksMap = new HashMap<>()
你也應該通過一個接口,您充當點擊監聽器的ViewHolder。就像是。
public interface OnItemLick {
void onItemClick(int position, int id);
}
然後在適配器中聲明此接口的一個實例。
OnItemLick listener = new OnItemClick() {
void onItemClick(int position, int id) {
//you can either use the item position or an id (if you have an unique one for the items). I will show an example using the position.
int count;
if(clicksMap.contains(position)) {
count = clickMap.get(position);
count ++;
clickMap.put(position, count);
}else {
count ++;
clickMap.put(position, count); }
}
最後,clicksMap將包含回收站中物品每個位置的點擊數。
我做一個例子
CustomItem的對象
public class CustomItem {
private String item;
private int click;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getClick() {
return click;
}
public void setClick(int click) {
this.click = click;
}
}
CustomAdapter和用於recyclerview
public class CustomAdapter extends RecyclerView.Adapter{
private List<CustomItem> itemList;
public CustomAdapter(List<CustomItem> itemList){
this.itemList = itemList;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new CustomViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.viewholder_generic, parent, false));;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//increase click count for the current item
itemList.get(holder.getAdapterPosition()).setClick(itemList.get(holder.getAdapterPosition()).getClick() + 1);
}
});
}
@Override
public int getItemCount() {
return itemList.size();
}
// Custom ViewHolder
public class CustomViewHolder extends RecyclerView.ViewHolder {
//add fields you need
public CustomViewHolder(View itemView) {
super(itemView);
}
}
}
CustomViewHolder
首先聲明靜態變量計數爲每個項目
private static int aCount = 0;
然後你onBindViewHolder內,通過該按鈕後點擊連同您的位置ID的方法。
public void onBindViewHolder(ItemAdapter.ViewHolder holder, int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
thisWasClicked(position);
}
}
}
的方法是這樣的
private void thisWasClicked(int position) {
if (position == 0) {
aCount++;
}
}
我已經做到了。我需要計算該特定項目的點擊次數。 @GiacomoLai –
你可以發佈你是如何填充recyclerview中的數據,你如何在recyclerview上應用onCLick? – AbhayBohra