我创建了一个应用,并希望我的操作栏上有一个后退按钮,可以使用Android Studio导航回上一页。我查看了一些示例,但在setDisplayHomeAsUpEnabled
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
public boolean onOptionsItemSelected(MenuItem item) {
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
// 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
答案 0 :(得分:9)
假设您有一个DetailActivity,并且您需要返回MainActivity按钮。首先将清单更改为DetailActivity
<activity
android:name=".DetailActivity"
android:label="@string/title_activity_detail"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.MainActivity"/>
</activity>
并在DetailActivity的onCreate
中
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
会解决问题。这是最简单的实现。
答案 1 :(得分:0)
在onCreate()
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
在MainActivity.java
类
protected OnBackPressedListener onBackPressedListener;
public interface OnBackPressedListener {
void doBack();
}
public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
this.onBackPressedListener = onBackPressedListener;
}
@Override
public void onBackPressed() {
if (onBackPressedListener != null)
onBackPressedListener.doBack();
else
super.onBackPressed();
}
现在,在Fragment类中,您可以实现MainActivity.OnBackPressedListener
而不是:
@Override
public void doBack() {
//Do on back pressed operation
}
答案 2 :(得分:0)
让您的活动延伸AppCompatACtivity
,然后将navigationIcon
设置为toolbar
以及clicklistener
例如
public class MyActivity extends AppCompatActivity {
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_arrow); // Set the icon
// Icon click listener
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("cek", "home selected");
}
});
}
}
确保您的活动主题为AppCompat
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- Customization will goes here -->
</style>
答案 3 :(得分:0)
//In Kotlin
// go to AndroidManifest.xml file apply this change
<activity android:name=".PresentActivity">
// for adding back button on top
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value=".BackActivity"/>
</activity>
// Hope this will work.