본문으로 건너뛰기

webview-with-edittext

webViewWithEditText in Android Studio

이 글은 기존 블로그의 원문에서 가져왔습니다. 원문 작성일: 2021-08-02

WebViewWithEditText

sharedPreferences, webView, Navigation in Android Studio

위 페이지에서 만든 webView에다가 EditText를 이용해서 URL 입력 창을 만들 것이다.

앞에서 webView에 대한 거의 모든 기능들을 구현해놨기 때문에 일단 EditText 위젯을 추가해줬다.

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
 
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/etForURL" />
 
    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
 
 
</LinearLayout>

 linearLayout을 이용해서 밑의 사진과 같이 다른 인터넷 브라우저처럼 깔끔하게 위젯을 배치했다.

그리고 java파일에 아래와 같은 코드를 추가했다.

etForURL = (EditText)findViewById(R.id.etForURL);
etForURL.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        url = etForURL.getText().toString();
        webView.loadUrl(url);
        return true;
    }
});

1- EditText 변수에 실제 위젯을 findViewById()을 이용해서 연결해줬다.

2~9- SetOnEditorActionListener()을 이용해서 EditText 위젯을 편집했을 때 이벤트를 발생시키도록 했다.

5- EditText에서 getText()로 받아온 text를 toString()을 이용해서 string의 형태로 url에 저장했다.

6- loadUrl을 이용해서 받아온 url의 웹페이지를 webView에 띄우도록 했다.