我在MainActivity
创建了徽章。它完美地从活动中完成。但在MainActivity
中,我已经ViewPager
,我需要增加片段的徽章数量。知道如何实现这个目标吗?
@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);
}
这是徽章计数增量
的方法 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();
}
答案 0 :(得分:0)
首先创建一个新的接口类
public interface OnStepCompletedListener {
void onStepCompleted(int position);
}
现在在Activity类中实现此接口。
public class MainActivity extends AppCompatActivity implements OnStepCompletedListener{
并实施该方法(在您的活动中)
@Override
public void onStepCompleted(int position){
//
// invoke method to change the badge number here
//
}
现在在你的片段里面。将此代码添加到您想要更改徽章的位置。(在' +'按钮点击内)
try{
((OnStepCompletedListener) getActivity()).onStepCompleted(0);
//This will invoke the implemented method in your activity class. You
//can pass any type of value through to your activity. Just add the
//parameter in your interface declaration.
}catch (ClassCastException e){
e.printStackTrace();
}
答案 1 :(得分:-1)
将count变量定义为static并从菜单布局类访问它,从而将静态计数的值放到textview上。 我已经从片段中添加了菜单,这是代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
}