Android:从Recycler Adapter

时间:2017-03-25 11:42:34

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

我正在尝试开发电子商务类型的应用,用户可以将商品添加到购物车。但是我无法从适配器更新购物车徽章计数器。 这是我的应用程序的屏幕截图。

enter image description here

我在片段中使用Recycler视图。我在下面的链接中提到菜单项目计数。

https://mobikul.com/adding-badge-count-on-menu-items-like-cart-notification-etc/

我的问题是我无法从适配器访问菜单项。

这是我的片段代码。

  

PriceListFragment.java

public class PriceListFragment extends Fragment {

    public ArrayList<Design> designList;
    private Single_DesignAdapter adapter;
    private RecyclerView recyclerView;

    public PriceListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        setHasOptionsMenu(true);
        View v = inflater.inflate(R.layout.fragment_price_list, container, false);

        recyclerView = (RecyclerView)v.findViewById(R.id.pl_recycler_view);

        designList = new ArrayList<Design>();

        designList = list();

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setHasFixedSize(true);
        adapter = new Single_DesignAdapter(getContext(), designList);
        recyclerView.setAdapter(adapter);

        return v;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.cart_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);

        MenuItem itemCart = menu.findItem(R.id.menu_cart);
        LayerDrawable icon = (LayerDrawable) itemCart.getIcon();
        setBadgeCount(getContext(), icon, 0);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.menu_cart:
                Toast.makeText(getActivity(), "cart", Toast.LENGTH_SHORT). show();
                return false;


            default:
                break;
        }
        return false;

    }

    public ArrayList<Design> list() {
        ArrayList<Design> arrayList = new ArrayList<Design>();

        Design design = new Design();
        design.name = "Black";
        design.image = "http://website/Demo/images/1.jpg";
        design.designName = "11001";
        design.qualityName = "Cotton";
        design.amount = "1000";
        design.discPercent = "5";

        Design design2 = new Design();
        design2.name = "Green";
        design2.image = "http://website/Demo/images/2.jpg";
        design2.designName = "11001";
        design2.qualityName = "Cotton";
        design2.amount = "900";
        design2.discPercent = "9";

        arrayList.add(design);
        arrayList.add(design2);

        return arrayList;
    }

    public static void setBadgeCount(Context context, LayerDrawable icon, int count) {

        BadgeDrawable badge;

        // Reuse drawable if possible
        Drawable reuse = icon.findDrawableByLayerId(R.id.ic_badge);
        if (reuse != null && reuse instanceof BadgeDrawable) {
            badge = (BadgeDrawable) reuse;
        } else {
            badge = new BadgeDrawable(context);
        }

        badge.setCount(count);
        icon.mutate();
        icon.setDrawableByLayerId(R.id.ic_badge, badge);
    }
}

设计是我的模型类

  

Design.java

public class Design implements Serializable{

    public String id;
    public String qualityId;
    public String qualityName;
    public String designId;
    public String designName;
    public String image;
    public String name; //use as shade name
    public String discPercent;
    public String amount;
    public String pcs;
    public String qty;
}
  

Single_DesignAdapter.java

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

    public ArrayList<Design> designList;
    private Context context;
    private LayoutInflater layoutInflater;

    public Single_DesignAdapter(Context context, ArrayList<Design> designList) {
        this.designList = designList;
        this.context = context;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.single_design, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        Design design = designList.get(position);
        holder.tvQuality.setText(design.qualityName);
        holder.tvDesign.setText(design.designName);
        holder.tvShade.setText(design.name);
        if (!design.discPercent.equals("0")) {
            holder.tvDisPer.setText("-"+design.discPercent+"%");
            holder.tvAmount.setPaintFlags(holder.tvAmount.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            int a = Integer.parseInt(design.amount);
            float b = Float.parseFloat(design.discPercent) / 100;
            holder.tvAmount.setText("₹ " + design.amount);
            int c = (int) (a * b);
            int d = a-c;
            holder.tvDiscAmt.setText("₹ " +d);
            Picasso.with(context).load(design.image).into(holder.ivDesign);
        } else {
            holder.tvAmount.setText("₹ " + design.amount);
            Picasso.with(context).load(design.image).into(holder.ivDesign);
            holder.tvDisPer.setVisibility(View.INVISIBLE);
            holder.tvDiscAmt.setVisibility(View.INVISIBLE);
        }

        holder.btAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                holder.llAdd.setVisibility(View.GONE);
                holder.llPlusMinus.setVisibility(View.VISIBLE);
            }
        });

        holder.btPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Integer.parseInt(holder.btPcsCount.getText().toString()) >= 1) {
                    int a = Integer.parseInt(holder.btPcsCount.getText().toString());
                    int x = a++;
                    holder.btPcsCount.setText(Integer.toString(a));
                }
            }
        });

        holder.btMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Integer.parseInt(holder.btPcsCount.getText().toString()) <= 1) {
                    holder.llAdd.setVisibility(View.VISIBLE);
                    holder.llPlusMinus.setVisibility(View.GONE);
                } else {
                    int a = Integer.parseInt(holder.btPcsCount.getText().toString());
                    a--;
                    holder.btPcsCount.setText(Integer.toString(a));
                }
            }
        });

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {

        public LinearLayout llPer, llAdd, llPlusMinus;
        public Button btPlus, btMinus, btPcsCount, btAdd;
        public ImageView ivDesign;
        public TextView tvDesign, tvQuality, tvShade, tvAmount, tvDiscAmt, tvDisPer;

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

            btPlus = (Button) itemView.findViewById(R.id.btPlus);
            //other find view by ids
        }
    }
}

现在,当用户将项目添加到购物车时,它应该增加计数器。我将在ArrayList<Design>中添加每个购物车项目,然后我将此列表保存为共享首选项。我将管理一切,但我无法理解如何从适配器更新购物车的计数器。我无法访问适配器中的菜单。如果还有其他办法,请帮助。

4 个答案:

答案 0 :(得分:1)

在您的片段点击事件中:

((MainActivity) getActivity()).createCartBadge("value");

您的活动包含以下方法:

public void createCartBadge(int i) {
        MenuItem cartItem = mToolbarMenu.findItem(R.id.cart);
        LayerDrawable localLayerDrawable = (LayerDrawable) cartItem.getIcon();
        Drawable cartBadgeDrawable = localLayerDrawable
                .findDrawableByLayerId(R.id.ic_badge);
        BadgeDrawable badgeDrawable;
        if ((cartBadgeDrawable != null)
                && ((cartBadgeDrawable instanceof BadgeDrawable))
                && (i < 10)) {
            badgeDrawable = (BadgeDrawable) cartBadgeDrawable;
        } else {
            badgeDrawable = new BadgeDrawable(MainActivity.this);
        }
        badgeDrawable.setCount(i);
        localLayerDrawable.mutate();
        localLayerDrawable.setDrawableByLayerId(R.id.ic_badge, badgeDrawable);
        cartItem.setIcon(localLayerDrawable);
    }

答案 1 :(得分:1)

由于Context已经有Adapter。你可以把它强制转换为Activity。这样您就可以访问菜单了。

//when item is added or removed
((Activity)this.context).invalidateOptionsMenu()

Fragment.onCreateOptionsMenu中,您可以继续设置项目计数

答案 2 :(得分:0)

您可以使用InterfaceFragmentAdapter之间进行通信。

例如:

public interface CallbackInterface {
    void onCall();
}

并在PriceListFragment onCreateView中执行此操作:

CallbackInterface callback = new CallbackInterface{
 @Override
  public void onCall() {
     if(itemCart!=null){
       //code to increment badge
     }
  }
};

并将callback传递给适配器的构造函数,然后在那里使用它。

答案 3 :(得分:0)

您现在可以在TextView使用徽章样式,您需要做的就是调整文本视图位置,使其看起来像徽章。

        <TextView
                android:id="@+id/fabCounter"
                style="@style/Widget.Design.FloatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true"
                android:layout_marginEnd="10dp"
                android:padding="5dp"
                android:text="-9"
                android:textColor="@android:color/black"
                android:textSize="14sp" />
  

Result