有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在按下actionbar或内置后退按钮时启动Intent

所以我想在按下两个后退按钮时启动。此后退按钮“getSupportActionBar().setDisplayHomeAsUpEnabled(true);”或者是所有安卓手机上的内置设备。我到处找,找不到解决办法

这是我的代码,您可以在if语句中看到,我希望“if back button is pressed”代码为。我很感激任何意见

    CheckBox routeCheckBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_route_details);

    //back button for route details view
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //sets actionbar title
    routeName = getIntent().getExtras().getString("routeName");
    getSupportActionBar().setTitle(routeName);


    ///////checkbox///////
    routeCheckBox = (CheckBox) findViewById(R.id.routeCheckBox);

    routeCheckBox.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view)
        {
          if (routeCheckBox.isChecked())
          {
              Intent check = new     Intent(RouteDetails.this,MainActivity.class);
              check.putExtra("checkImageResource", R.drawable.checkmark);

  /////////////////// ////////////     
              if ( actionbar back button or the built in backbutton on all   安卓 devices is pressed)
              {
                  startActivity(check);
              } 
     ////////////////////////////////
          }
        }
    });

新代码编辑:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case 安卓.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    // your code here
    routeCheckBox.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view)
        {
            if (routeCheckBox.isChecked())
            {
                Intent check = new Intent(RouteDetails.this,MainActivity.class);
                check.putExtra("checkImageResource", R.drawable.checkmark);
                startActivity(check);
            }
        }
    });
}

共 (1) 个答案

  1. # 1 楼答案

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        // your code here
    }