I've created badge in MainActivity
. It's working perfectly from activity. But in MainActivity
, I've taken ViewPager
and I need to increase badge count from fragment. Any idea how to achieve this?
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.cart_menu, menu);
menuItem = menu.findItem(R.id.action_cart);
menuItem.setIcon(buildCounterDrawable(count, R.drawable.ic_cart));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_cart) {
Intent intent = new Intent(this, CartActivity.class);
intent.putExtra("id", orderid);
startActivityForResult(intent, PICK_REQUEST);
return true;
}
return super.onOptionsItemSelected(item);
}
This is the method for Badge count increment
private Drawable buildCounterDrawable(int count, int backgroundImageId) {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
view.setBackgroundResource(backgroundImageId);
if (count == 0) {
View counterTextPanel = view.findViewById(R.id.counterValuePanel);
counterTextPanel.setVisibility(View.GONE);
} else {
TextView textView = (TextView) view.findViewById(R.id.count);
textView.setText(String.valueOf(count));
}
view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return new BitmapDrawable(getResources(), bitmap);
}
public void doIncrease(int val) {
count = val;
invalidateOptionsMenu();
}
On Click of plus button, I need to increase the count. Totally unaware how to achieve this
First Create a new Interface Class
Now implement this interface in your Activity class.
and implement the method(in your activity)
Now inside your fragment. Add this code where you want to change the badge.(inside the '+' button click)