2015-04-27 76 views
1

使用Android Studio我开发了我的第一个基于WebView的应用程序。 在menu.xml文件中,我定义了一些选项,如设置,我希望如果任何用户点击它,url.comsettings应该在WebView中打开。 menu_main.xml如下如何从menu.xml打开链接到WebView

<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); 
    } 
} 

回答

1

可以使用onOptionsItemSelected()方法本身加载网址,取决于操作栏按钮的点击。

@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); 
} 
+0

谢谢亲爱的!有效。嘿!有没有办法刷新当前页面? – Disk01

+0

没问题:)。您可以再次调用相同的方法mWebView.loadUrl(“http://www.example.com/settings”); – Kottary