1. Cấp quyền Internet cho ứng dụng
1 |
<uses-permission android:name="android.permission.INTERNET"/> |
2. Tạo Layout: activity_web_view.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".WebViewActivity"> <WebView android:id="@+id/web_view" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> |
3. Tạo Class: WebViewActivity
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; public class WebViewActivity extends AppCompatActivity { private WebView webView; private String newsURL; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getSupportActionBar().hide(); setContentView(R.layout.activity_web_view); Intent intent = getIntent(); newsURL = intent.getStringExtra("EXTRA_URL_LINK"); initView(); } private void initView() { webView = findViewById(R.id.web_view); webView.setWebViewClient(new WebViewClient()); webView.loadUrl(newsURL); } @Override public void onBackPressed() { if (webView.canGoBack()){ webView.goBack(); } else { super.onBackPressed(); } } } |
4. Sử dụng
1 2 3 4 5 6 7 |
String pathOffline = "/TestDownload/" + "file_name" + ".html"; String linkOffline = "file:///"+ pathOffline; String linkOnline = "https://www.google.com/"; Intent webViewIntent = new Intent(mainActivity, WebViewActivity.class); webViewIntent.putExtra("EXTRA_URL_LINK", linkOnline); //webViewIntent.putExtra("EXTRA_URL_LINK", linkOffline); startActivity(webViewIntent); |