2011-03-07 89 views
27

我試圖在佈局main.xml中設置WebView上的URL。如何在Android上的xml佈局文件中設置WebView上的url?

通過代碼很簡單:

WebView webview = (WebView)findViewById(R.id.webview); 
    webview.getSettings().setJavaScriptEnabled(true); 
    webview.loadUrl("file:///android_asset/index.html"); 

有沒有把這個邏輯到佈局xml文件的簡單方法?

+5

注意名稱_layout_ xml文件。我不認爲有任何方法可以從XML做到這一點。我明白了你的觀點,你希望能夠在設備上加載數據而無需從代碼加載url,但我認爲現在沒有任何支持。 – 2011-03-07 12:53:05

+0

Cant0na看到我的觀點的目標! – 2011-03-07 13:06:43

回答

-2

由於URL基本上是一個字符串,可以把它放到價值/ strings.xml檔案

<resources> 
    <string name="myurl">http://something</string> 
</resources> 

那麼你可以使用它像這樣:

WebView webview = (WebView)findViewById(R.id.webview); 
webview.getSettings().setJavaScriptEnabled(true); 
webview.loadUrl(getString(R.string.myurl)); 
+33

我想他正在嘗試找到一些方法來直接在xml文件中設置url,而無需在Activity中運行loadUrl方法。像: 2011-03-07 13:06:17

+0

感謝您的建議。這無疑是一種將url從代碼中移出並存入res文件的方式,我希望能夠直接從layout xml文件中獲得url,而不是被迫通過運行loadUrl(...)碼。 – 2011-03-07 13:08:35

+22

這不應該是選定的答案。它不回答這個問題。 – Rob 2014-03-27 21:37:36

3

你可以聲明自定義視圖並按照here所述應用自定義屬性。

結果將類似於此:

在佈局

<my.package.CustomWebView 
     custom:url="@string/myurl" 
     android:layout_height="match_parent" 
     android:layout_width="match_parent"/> 

在attr.xml

<resources> 
    <declare-styleable name="Custom"> 
     <attr name="url" format="string" /> 
    </declare-styleable> 
</resources> 

終於在自定義的Web視圖類

public class CustomWebView extends WebView { 

     public CustomWebView(Context context, AttributeSet attributeSet) { 
      super(context); 

      TypedArray attributes = context.getTheme().obtainStyledAttributes(
        attributeSet, 
        R.styleable.Custom, 
        0, 0); 
      try { 
       if (!attributes.hasValue(R.styleable.Custom_url)) { 
        throw new RuntimeException("attribute myurl is not defined"); 
       } 

       String url = attributes.getString(R.styleable.Custom_url); 
       this.loadUrl(url); 
      } finally { 
       attributes.recycle(); 
      } 
     } 
    } 
+3

您仍在使用代碼。這比他發佈的三行代碼更有效。沒有? – TheRealChx101 2017-03-23 06:38:38

+1

當然,這是更多的工作,但問題是如何通過佈局定義設置網址。這是這樣做的唯一方法。 – loklok 2017-03-23 08:56:35