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?
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.
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.
Within the shouldOverrideUrlLoading() method simply get the URL from the request and pass into the Intent. See the full example.
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.
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(); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With