Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set URL for WebView from layout XML in Android?

I'm trying to set the URL for a WebView from the layout main.xml.

By code, it's simple:

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

Is there a simple way to put this logic into the layout XML file?

like image 906
Vidar Vestnes Avatar asked Mar 07 '11 12:03

Vidar Vestnes


People also ask

How do I display HTML content in WebView?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken web view to show html content.

What is the WebView layout on Android?

The WebView class is an extension of Android's View class that allows you to display web pages as a part of your activity layout. It does not include any features of a fully developed web browser, such as navigation controls or an address bar. All that WebView does, by default, is show a web page.

How do I open a link in WebView?

Within the shouldOverrideUrlLoading() method simply get the URL from the request and pass into the Intent. See the full example.

How do I import WebView?

Modify src/MainActivity. java file to add WebView code. Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified main activity file src/MainActivity.


1 Answers

You can declare your custom view and apply custom attributes as described here.

The result would look similar to this:

in your layout

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

in your attr.xml

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

finally in your custom web view class

    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();             }         }     } 
like image 75
loklok Avatar answered Sep 26 '22 01:09

loklok