Android Up按钮无效

spo*_*oss 5 java android r.java-file android-activity android-studio

我正在尝试手动实现按下操作栏上的向上按钮时必须执行的操作,但出于某种原因,当我按下它时没有任何反应.

这是我的代码:

public class ActivityOne extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity_one);
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_actionbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Button button = (Button)findViewById(R.id.btn1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openActivityTwo();
            }
        });
        Button button2 = (Button)findViewById(R.id.btn2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openActivityThree();
            }
        });
    }


    void openActivityTwo(){
        Intent intent = new Intent(this, ActivityTwo.class);
        startActivity(intent);
    }

    void openActivityThree(){
        Intent intent = new Intent(this, ActivityThree.class);
        startActivity(intent);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_activity_one, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        else if(id == R.id.homeAsUp){
            Log.i("","Up is pressed");
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道我必须明确为我要在清单文件上实现导航的活动分配一个父活动,但问题是这个活动有多个父,所以我想finish()在这个活动上按下向上按钮时调用方法将是更好的方法.

我已经尝试了两者id == R.id.home并且id == R.id.homeAsUp它们都不起作用.我不知道是不是因为我正在使用AppCompactActivity或者请帮忙

Ami*_*ela 11

以下是如何实现此功能,请尝试此代码

使用android.R.id.home而不是R.id.home或R.id.homeAsUp

public boolean onOptionsItemSelected(final MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                //use onBackPressed() OR finish();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }
Run Code Online (Sandbox Code Playgroud)