应用程序工具栏上的HomeButton停止工作

时间:2018-07-20 17:09:17

标签: android performance android-toolbar

我需要HomeButton才能使用户返回MainActivity,但突然它停止了工作。在其他活动中,没有这种问题,但是代码是相同的。


MyActivity.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>

3 个答案:

答案 0 :(得分:0)

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

@Override
public void onBackPressed() {
    super.onBackPressed();
}

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

答案 1 :(得分:0)

如果使用默认的AppTheme,则应该已经有一个工具栏。而且,如果您在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>

希望这会有所帮助

答案 2 :(得分:0)

导航模式在某些情况下需要您手动指定“后退”行为。

可以通过以下方式完成:

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

有关使用Webview进行更详细的向后导航,请访问开发者网站 [https://developer.android.com/training/implementing-navigation/temporal]

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

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

它必须具有super.onOptionsItemSelected(item),默认反向导航才能起作用。