如何在onMenuItemClick()中更新菜单项标题

时间:2018-03-04 08:16:07

标签: android

我已将cardview创建为RecyclerView的单个项目 在我的cardview中,我以编程方式创建了一个弹出菜单..

我想在运行时更改菜单项的标题

是否可以在onMenuItemClick()方法中更新菜单项标题?

我的HomeFragment.java看起来像 -

 private void showPopupMenu(View view, int position,String post_key) {

    // inflate menu
    PopupMenu popup = new PopupMenu(view.getContext(),view );
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.card_view_menu, popup.getMenu());
    popup.setOnMenuItemClickListener(new MyMenuItemClickListener(position,post_key));
    popup.show();
}


class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {

private int position;
DatabaseReference mPostDatabase;
private String post_key;
Menu menu;

 MyMenuItemClickListener(int positon,String post_key) {
    this.position = positon;
    this.post_key=post_key;
    mPostDatabase=FirebaseDatabase.getInstance().getReference().child("Posts");
}


@Override
public boolean onMenuItemClick(final MenuItem item) {

    int id=item.getItemId();

    switch (id){

        case R.id.delete_post:

          mPostDatabase.addValueEventListener(new ValueEventListener() {
              @Override
              public void onDataChange(DataSnapshot dataSnapshot) {

                  if(dataSnapshot.hasChild(post_key)){

                      String from_id= String.valueOf(dataSnapshot.child(post_key).child("from").getValue());

                      if(from_id.equals(FirebaseAuth.getInstance().getCurrentUser().getUid())){

                          mPostDatabase.child(post_key).removeValue();
                      }
                      else {

                      //here i want to change the title              
                      item.setTitle("Save Post");//it doesn't work
                      }
                  }
              }

              @Override
              public void onCancelled(DatabaseError databaseError) {

              }
          });

    }
    return false;
}

}

1 个答案:

答案 0 :(得分:0)

这一行之后:

//here i want to change the title              
item.setTitle("Save Post");

调用以下功能

invalidateOptionsMenu();