我正在尝试手动实现当操作栏上的向上按钮被按下时必须执行的操作,但出于某种原因,当我按下它时什么也没有发生。
这是我的代码:
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);
}
}
我知道必须在清单文件中显式指定一个父活动,以便为我想要实现向上导航的活动分配父级,但问题是这个活动有多个父级,因此我认为在按下此活动上的向上按钮时调用finish()
方法会是更好的方法。
我已经尝试了id == R.id.home
和id == R.id.homeAsUp
,它们都不起作用。我不知道是否因为我正在使用AppCompactActivity
或其他原因。请帮帮我。