应用程序工具栏上的主页按钮已停止工作



我需要HomeButton将用户返回到MainActivity,但它突然停止工作。在其他活动中没有这样的问题,但代码是一样的。


我的活动.java

private Toolbar mToolbar;
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
mToolbar = (Toolbar) findViewById(R.id.my_app_bar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("...");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
webView = (WebView) findViewById(R.id.my_activity_webview);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("...");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
/*@Override
public void onBackPressed() {
super.onBackPressed();
}*/

MyActivity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity"
android:orientation="vertical">
<include
android:id="@+id/my_app_bar"
layout="@layout/app_bar_layout"></include>
<WebView
android:id="@+id/my_activity_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

在您的活动中添加以下代码:

@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}

如果使用默认的AppTheme,则应该已经有了Toolbar。如果你在AndroidManifest.xml中设置了父活动,它应该会自动完成。

<activity android:name=".MainActivity">
<!--sets the launcher-->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewActivity">
<!--sets the parent activity-->
<meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity"  />
</activity>

希望这能帮助

在某些情况下需要手动指定Back行为的导航模式。

可通过以下方式完成:

通过向activity元素添加android:parentActivityName属性来指定清单中的父活动。

有关webview的详细反向导航,请查看开发人员网站[https://developer.android.com/training/implementing-navigation/temporal]

其他可能性:如果你有该活动的菜单,并且已经覆盖,

@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}

它必须具有super.onOptionsItemSelected(item)才能使默认的反向导航工作。

最新更新