我向Toolbar
添加了Activity
,并带有后退箭头,如下所示:
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
//add back arrow - but it doesn't go back, nothing happens when I click it
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
但是当我单击后退箭头时,它不会返回上一页
答案 0 :(得分:1)
添加以下行:
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish(); // or your code
}
答案 1 :(得分:0)
您需要像这样覆盖onCreateOptionsMenu()
和onOptionsItemSelected()
:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_id, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
别忘了用您的ID代替R.menu.your_id作为名称建议。
答案 2 :(得分:0)
根据建议的答案,您可能希望在Android manifest.xml中添加parentActivity
<application ... >
...
<!-- The main/home activity (it has no parent activity) -->
<activity
android:name="com.example.myfirstapp.MainActivity" ...>
...
</activity>
<!-- A child of the main activity -->
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<!-- The meta-data element is needed for versions lower than 4.1 -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>