IT/Android

android - 안드로이드 웹뷰(WebView)

노마드오브 2018. 9. 19. 21:59

파일명 : activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
android:id="@+id/editUrl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"></EditText>

<Button
android:id="@+id/btnG0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="이동" />

<Button
android:id="@+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="이전" />
</LinearLayout>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView1" />
</LinearLayout>



파일명 : MainActivity.java

package com.example.it.myapplication6_20;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
EditText editUrl;
Button btnGo, btnBack;
WebView web;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editUrl = (EditText) findViewById(R.id.editUrl);
btnGo = (Button) findViewById(R.id.btnG0);
btnBack = (Button) findViewById(R.id.btnBack);
web = (WebView) findViewById(R.id.webView1);

web.setWebViewClient(new CookWebViewClient());

WebSettings webSet = web.getSettings();
webSet.setBuiltInZoomControls(true);

btnGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
web.loadUrl(editUrl.getText().toString());
}
}
);

btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
web.goBack();;
}
}

);
}

class CookWebViewClient extends WebViewClient {

// 자동 오버라이드 : alt + enter 또는 ctrl + o
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
}
}