从列表中获取最后一个项目-在Recyclerview上单击添加按钮

时间:2018-12-07 14:41:17

标签: android android-recyclerview recycler-adapter android-button

我在Adapter类中添加了购物车图像,但是每当我单击按钮时,总是从列表中获取最后一个元素。这是我的适配器类和活动类。 从firebase和显示菜单列表的Log文件中可以完美地获取详细信息。

这是我的MenuAdapter.java类。

public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {

private Context mCtx;
private List<Menu> menuList;
private ItemClickEvent itemclick;


public MenuAdapter(Context mCtx, List<Menu> menuList, ItemClickEvent itemclick) {
    this.mCtx = mCtx;
    this.menuList = menuList;
    this.itemclick = itemclick;
}

@NonNull
@Override
public MenuViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) 
{
    View view = LayoutInflater.from(mCtx).inflate(R.layout.menu_list, viewGroup, false);
    return new MenuViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final MenuViewHolder menuViewHolder, final int i) {
    final Menu menu = menuList.get(i);
    menuViewHolder.itemName.setText(menu.itemName);
    menuViewHolder.itemPrice.setText(menu.itemPrice);
    menuViewHolder.addCart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            itemclick.imageClicked(menu);
        }
    });
}

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

public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView itemName, itemPrice;
    @SuppressLint("StaticFieldLeak")
    ImageView addCart;

    MenuViewHolder(@NonNull View itemView) {
        super(itemView);

        itemName = itemView.findViewById(R.id.itemName);
        itemPrice = itemView.findViewById(R.id.itemPrice);
        addCart = itemView.findViewById(R.id.menuAddCart);
        //addCart.setOnClickListener(this);
        itemView.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {


    }

}

}

和这个MenuActivity.java类

public class MenuActivity extends AppCompatActivity implements ItemClickEvent 
{

private ActionBar toolbar;
List<Menu> menuList;
RecyclerView recyclerView;
MenuAdapter adapter;
DatabaseReference databaseReference;
ProgressBar progressBar;
Menu menu;
int foodId = 1;
int cat;
String id,itemName, itemPrice;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);
    Intent intent = getIntent();
    final String category = intent.getStringExtra("cat_id");
    final String catName = intent.getStringExtra("cat_name");
    toolbar = getSupportActionBar();
    toolbar.setTitle(catName);
    cat = Integer.parseInt(category) - 1;

    menuList = new ArrayList<>();
    recyclerView = findViewById(R.id.menu_recycler);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new MenuAdapter(this, menuList,this);
    recyclerView.setAdapter(adapter);
    ImageView addTCart = findViewById(R.id.menuAddCart);
    progressBar = findViewById(R.id.progressBarLoading);
    databaseReference = FirebaseDatabase.getInstance().getReference("foods/" + cat + "/menu-items");
    // fetchMenu(category);
    progressBar.setVisibility(View.VISIBLE);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() 
{
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            progressBar.setVisibility(View.GONE);
            if (dataSnapshot.exists()) {
                for (DataSnapshot wallpaperSnapshot : dataSnapshot.getChildren()) {

                    id = wallpaperSnapshot.getKey();
                    itemName = wallpaperSnapshot.child("name").getValue(String.class);
                    itemPrice = wallpaperSnapshot.child("price").getValue(String.class);

                    menu = new Menu(id, itemName, itemPrice, category);

                    menuList.add(menu);
                    Log.d("FOOD-DETAIL", String.valueOf(menu));
                }
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


}

@Override
public void imageClicked(Menu m) {
    new Database(getApplicationContext()).addToCart(new Order(
            Integer.parseInt(id),
            menu.getItemName(),
            "1",
            menu.getItemPrice()
    ));
    foodId += 1;
    Toast.makeText(getBaseContext(), itemName+" added to cart", Toast.LENGTH_SHORT).show();

}

@Override
public void viewClicked() {

}
}

2 个答案:

答案 0 :(得分:0)

您好尝试在MenuActivity的imageClicked()中进行这些更改

@Override
 public void imageClicked(Menu m) {
    new Database(getApplicationContext()).addToCart(new Order(
            m.getId(),
            m.getItemName(),
            "1",
            m.getItemPrice()
    ));
    foodId += 1;
    Toast.makeText(getBaseContext(), itemName+" added to cart", Toast.LENGTH_SHORT).show();

}

答案 1 :(得分:0)

应该有更有效的方法来设置监听器。只需在MenuViewHolder的构造函数中设置该侦听器(与现在相同),然后分配给它即可。然后在onClick方法中-检查视图的R.id,是否为addCart而不是调用itemclick.imageClicked(menu),只需调用item.click.imageClicked(getAdapterPosition())

这是因为onBindViewHolder()被多次调用,您仍将创建新的侦听器。但是在构造函数中,仅当需要新的MenuViewHolder并使用适配器的实际位置时,才创建该侦听器。