【问题标题】:How to open links into WebView from menu.xml如何从 menu.xml 打开链接到 WebView
【发布时间】:2026-02-20 16:35:01
【问题描述】:

使用 Android Studio,我开发了我的第一个基于 WebView 的应用程序。 在menu.xml 文件中,我定义了某些选项,例如设置,我希望如果任何用户单击它,URL example.com/setting 应该在 WebView 中打开。 menu_main.xml如下

<menu 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" tools:context=".MainActivity">
    <item android:id="@+id/action_settings" android:title="@string/action_settings"
        android:orderInCategory="100" app:showAsAction="never" />
</menu>

MainActivity.java如下

package com.example.app;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;


public class MainActivity extends ActionBarActivity {


   private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mWebView = (WebView) findViewById(R.id.activity_main_webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.example.com?ref=app");
        mWebView.setWebViewClient(new MyAppWebViewClient());
    }

    @Override
    public void onBackPressed() {
        if(mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }


    @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_main, 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;
        }

        return super.onOptionsItemSelected(item);
    }
}

【问题讨论】:

    标签: java android xml webview


    【解决方案1】:

    您可以使用onOptionsItemSelected() 方法本身来加载url,具体取决于操作栏按钮的点击。

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
    
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            mWebView.loadUrl("http://www.example.com/settings");
            return true;
        }
    
        return super.onOptionsItemSelected(item);
    }
    

    【讨论】:

    • 谢谢亲爱的!有效。嘿!有没有办法刷新当前页面?
    • 没问题 :) 。可以再次调用相同的方法 mWebView.loadUrl("example.com/settings");
    最近更新 更多