从活动返回时更改menuitem

时间:2015-11-18 09:57:41

标签: java android

当我从另一个活动返回到将进入新意图的设置时,我想更改菜单的menuitem寄存器。单击menu_item中的register时,活动将转到RegisterActivity。从RegisterActivity返回时,我想将菜单项寄存器更改为设置。

package com.mausamakasvani.srsk.mausamakasvani;


public class LoginActivity extends AppCompatActivity {
    private EditText password;
    private EditText userName;
    public static boolean Register;
    public static final int REG_REQ_CODE = 235;
    private int x = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ActionBar as = getSupportActionBar();
        as.setTitle("Login");
        userName = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);
    }
    public void onLoginClicked(View view){
        /*
        */
        if (!MausamCheckList.getStringValue(this,MausamCheckList.USER_NAME).equals(MausamCheckList.DEF_VALUE)) {
            if (userName.getText().toString().equals(MausamCheckList.getStringValue(this, MausamCheckList.USER_NAME)) && password.getText().toString().equals(MausamCheckList.getStringValue(this, MausamCheckList.PASSWORD))) {
                Intent intent = new Intent(this,SheharChunoActivity.class);
                startActivity(intent);
                //finish();
            }else {
                MausamCheckList.displayToast(this,"Username or Password is Wrong!!!");
            }
        }else{
            MausamCheckList.displayToast(this,"Please register");
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
           if(x==0)
            getMenuInflater().inflate(R.menu.menu_login, menu);

        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
            Intent intent = new Intent(this,RegisterActivity.class);
            startActivityForResult(intent,REG_REQ_CODE);
                        //startActivity(intent);
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REG_REQ_CODE) {
            if (resultCode == RegisterActivity.REG_RES_CODE) {
                x=RegisterActivity.REG_RES_CODE;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以将两个菜单项都包含在一个menu.xml文件中,具体取决于您要显示的特定项目的更改可见性。您可以在活动中简单地保持对Menu(并使用findItem方法)或MenuItem的引用,并像这样管理它(伪代码):

if(user.isRegistered()) {
   mSettingsMenuItem.setVisibility(View.VISIBLE);
   mRegisterMenuItem.setVisibility(View.GONE);
}

您也可以使用

public boolean onPrepareOptionsMenu (Menu menu)

每次调用菜单都显示在屏幕上,并根据条件显示正确的菜单项

Documentation for this