티스토리 뷰

Computer/Android

Android WebView 예제

jamezc 2013. 5. 27. 15:33

Android WebView예제를 작성해보았습니다. 이전에 작성했던 Fragment 예제에 추가되어있던 WebView인데 해당 글에서 설명을 하지 않아 따로 작성합니다. Fragment를 상속받을때와는 다르게 Activity를 상속받아 작성하였습니다. 사용된 예제는 주소 입력창과 Go 버튼을 추가하여 작성하였습니다.


사용한 API

 WebViewClient API

  http://developer.android.com/reference/android/webkit/WebViewClient.html

 사용한 상속 Public Method

 boolean

 shouldOverrideUrlLoading(WebView view, String url)
  - URL에 따른 페이지 Loding

 void

 onPageFinished(WebView view, String url)
  - 페이지 Loding이 완료되면 알려주는 Method


 WebChromeClient API

  http://developer.android.com/reference/android/webkit/WebChromeClient.html

 void

 onProgressChanged(WebView view, int newProgress)
  - 페이지의 현재 진행사항을 알려줍니다. (Loding 


 WebViewClient API는 기본적인 WebView의 화면을 보여주기 위해서 상속받아 작성하였고, WebChromeClient는 현재 페이지를 Loding하고, Finished 될 때 ProgressBar를 처리하기 위해서 상속받아 사용하였습니다.


예제 코드

Activity - WebView를 처리하는 코드입니다.

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package net.thdev.webviewexample;
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
 
@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
public class WebViewActivity extends Activity {
    private String mInputUrl = "http://www.google.com";
     
    private EditText mEditText;
    private WebView mWebView;
    private WebSettings mWebSettings;
    private ProgressBar mProgressBar;
    private InputMethodManager mInputMethodManager;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
         
        mEditText = (EditText)findViewById(R.id.edit_Url);
        mWebView = (WebView)findViewById(R.id.webview);
        mProgressBar = (ProgressBar)findViewById(R.id.progressBar);
        findViewById(R.id.btn_go).setOnClickListener(onClickListener);
         
        mInputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
         
        mWebView.setWebChromeClient(new webViewChrome());
        mWebView.setWebViewClient(new webViewClient());
        mWebSettings = mWebView.getSettings();
        mWebSettings.setBuiltInZoomControls(true);
         
        mWebView.loadUrl(mInputUrl);
        mEditText.setHint(mInputUrl);
    }
     
    //Button Event를 처리
    View.OnClickListener onClickListener = new View.OnClickListener() {
         
        @Override
        public void onClick(View v) {
            switch(v.getId()) {
            case R.id.btn_go:
                //InputMethodManager를 이용하여 키보드를 숨김
                mInputMethodManager.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
                mInputUrl = httpInputCheck(mEditText.getText().toString());
                 
                if(mInputUrl == null) break;
                 
                //페이지를 불러온다
                mWebView.loadUrl(mInputUrl);
                mEditText.setText("");
                mEditText.setHint(mInputUrl);
                break;
            }
        }
    };
     
    class webViewChrome extends WebChromeClient {
         
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //현제 페이지 진행사항을 ProgressBar를 통해 알린다.
            if(newProgress < 100) {
                mProgressBar.setProgress(newProgress);
            } else {
                mProgressBar.setVisibility(View.INVISIBLE);
                mProgressBar.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
            }
        }
    }
     
    class webViewClient extends WebViewClient {
         
        //Loading이 시작되면 ProgressBar처리를 한다.
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            mProgressBar.setVisibility(View.VISIBLE);
            mProgressBar.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 15));
            view.loadUrl(url);
            return true;
        }
         
        @Override
        public void onPageFinished(WebView view, String url) {
            mWebSettings.setJavaScriptEnabled(true);
            mEditText.setHint(url);
            super.onPageFinished(view, url);
        }
    }
     
    //http://를 체크하여 추가한다.
    private String httpInputCheck(String url) {
        if(url.isEmpty()) return null;
         
        if(url.indexOf("http://") == ("http://").length()) return url;
        else return "http://" + url;
    }
}

XML - WebView XML 예제코드입니다.

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
39
40
41
42
43
44
45
46
47
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
 
        <EditText
            android:id="@+id/edit_Url"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textUri"
            android:layout_weight="1"
            android:singleLine="true"
            android:hint="" />
 
        <Button
            android:id="@+id/btn_go"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:text="@string/btn_go"
            />
    </LinearLayout>
     
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:max="100"
        android:progress="0"
        android:secondaryProgress="1"
        android:visibility="invisible"
        style="?android:attr/progressBarStyleHorizontal"
        />
         
    <WebView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
         
    </WebView>
</LinearLayout>

추가한 Permission

1
<uses-permission android:name="android.permission.INTERNET" />

결과 화면

 간단하게 작성한 WebView입니다. 진행사항을 표시하기 위해서 WebViewChromeClient를 상속 받아 처리하였습니다. 잠시 보여지고 숨겨지는 간단한 ProgressBar를 추하였습니다. ActionBar를 사용해도 가능하지만 3.0 미만의 별도의 처리를 해야하기에 여기서는 제외시켰습니다. 다음에 ActionBar 예제를 다뤄보겠습니다. 이상 WebView 예제를 마치겠습니다.


다운로드

 다운로드는 예전에 작성해둔 Fragment의 Swipe 예제를 링크하겠습니다. 그 때 작성한 예제코드와 지금의 예제코드가 동일합니다. 아리 링크를 통해 다운로드 가능합니다.

  http://db.tt/dGZ5ckDq

댓글

파트너스 활동을 통해 일정액의 수수료를 제공받을 수 있음



Total
Today
Yesterday
최근에 달린 댓글