package self.mybrowser; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; public class MainActivity extends AppCompatActivity { private WebView myWebView; private EditText urlText; private static final String INITIAL_WEBSITE = "http://finance.yahoo.co.jp"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myWebView = (WebView) findViewById(R.id.myWebView); urlText = (EditText) findViewById(R.id.urlText); myWebView.getSettings().setJavaScriptEnabled(true); myWebView.setWebViewClient(new WebViewClient(){ @Override public void onPageFinished(WebView view, String url){ getSupportActionBar().setSubtitle(view.getTitle()); urlText.setText(url); } }); myWebView.loadUrl(INITIAL_WEBSITE); } public void clearUrl(View view){ urlText.setText(""); } public void showWebSite(View view){ String url = urlText.getText().toString().trim(); if (!Patterns.WEB_URL.matcher(url).matches()){ urlText.setError("Invalid URL"); } else { if(url.startsWith("http;//") && !url.startsWith("https://")){ url = "http://" + url; } myWebView.loadUrl(url); } } @Override public void onBackPressed(){ if (myWebView.canGoBack()){ myWebView.goBack(); return; } super.onBackPressed(); } @Override protected void onDestroy(){ super.onDestroy(); if(myWebView != null){ myWebView.stopLoading(); myWebView.setWebViewClient(null); myWebView.destroy(); } myWebView = null; } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="self.mybrowserapp.MainActivity"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:layout_weight="1" android:id="@+id/urlText" android:layout_width="0dp" android:onClick="clearUrl" android:inputType="text|textNoSuggestions" android:layout_height="wrap_content"/> <Button android:text="Browse" android:onClick="showWebsite" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <WebView android:layout_weight="1" android:id="@+id/myWebView" android:layout_width="match_parent" android:layout_height="0dp"></WebView> </LinearLayout>