在覆盖onOptionsItemSelected(MenuItem项)后,不再触发onSupportNavigateUp()

时间:2017-04-27 11:21:17

标签: java android

(很抱歉因为我在排查后发现实际问题而更改了整个问题)

我的活动如下:

public class MyAppActivity extends AppCompatActivity{
    @Override
    protected void onCreate(...)
    {
        //...
        this.setContentView(contentViewResID);
        Toolbar toolbar = (Toolbar) this.findViewById(toolbarResID);

        this.setSupportActionBar(toolbar);
        this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onPause() {...}

    @Override
    protected void onResume() {...}

    @Override
    public boolean onSupportNavigateUp() {
        Log.d("onSupportNavigateUp()", "pressed");
        finish();
        return super.onSupportNavigateUp();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {...}

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {...}

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item == menuAddFood) {
            Intent intent = new Intent(this, ActivityAddFood.class);
            this.startActivity(intent);
        }
        if (item == menuSettings){
            Intent intent = new Intent(this, ActivitySetting.class);
            this.startActivity(intent);

        }
        if(item == menuUsername){
        }
        return true;
    }
}

编辑:
经过我的问题排查后,我在覆盖onOptionsItemSelected()后发现了onSupportNavigateUp(),当我按下左上角后退/上/下按钮时,finish()不再解雇了。我想在onSupportNavigateUp()里面$("#opportunityTab").click(function(){ strCourseCat = $('#strCourseCat').val(); var strengthsData = ''; $.ajax({ success: function (response) {}, error: function (request, status, error) {} }); }); 如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您必须override当前Activity中的方法,并致电超级:

public class ActivityExample extends MyAppActivity {

    Context context = this;
    AppCompatActivity activity = this;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.createMyView(R.layout.activity_log_in, R.id.toolbar);
        // ...
    }

 @Override
    public boolean onSupportNavigateUp() {
     finish();
     return true;
    }

}

此外,如果您覆盖onOptionsItemSelected,则不会调用onSupportNavigateUp

//DONT OVERRIDE THIS METHOD
@Override
public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:

                break;
        }
        return true;
}