코틀린 웹뷰에서 리액트 화면 호출하기
기존에 react with typescript + spring boot 개발환경이 연계되어 있다는 가정하에 코틀린에서 웹뷰로 리액트 화면을 부르는 것을 목표로 한다.
react with typescript + spring boot 연계는 아래 글 참조
react + spring boot 연계하기
먼저 react 환경과 spring boot 백엔드 환경을 구축한다. 아래 글 2개를 참고한다. https://cgdev.tistory.com/43 react + typescript 개발환경 세팅하기먼저 Copilot에 물어보자물론입니다! React와 TypeScript를 함
cgdev.tistory.com
먼저 Copilot에 물어본다.
물론, 코틀린에서 웹뷰를 사용하여 리액트 화면을 호출하는 방법을 알려드리겠습니다. 리액트 화면은 http://localhost:3000에 위치하고 있습니다.
1. 인터넷 권한 설정: 먼저, AndroidManifest.xml 파일에 인터넷 권한을 추가해야 합니다. 아래와 같이 <uses-permission> 요소를 추가하세요:
XML
<uses-permission android:name="android.permission.INTERNET" />
AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.
2. 레이아웃에 WebView 추가: 웹뷰를 불러오는 동안 로딩바를 추가하기 위해 ProgressBar를 레이아웃에 추가합니다. activity_main.xml 파일에 다음과 같이 WebView와 ProgressBar를 추가하세요:
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/progress1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.
3. 웹뷰 호출: 가장 간단한 방법으로 웹뷰를 코드 두 줄로 호출할 수 있습니다. 하지만 이 방법은 많은 기능의 제약이 있습니다. loadUrl() 메서드를 사용하여 웹사이트를 호출할 수 있습니다:
Kotlin
val webView: WebView = findViewById(R.id.webView1)
webView.loadUrl("http://localhost:3000")
AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.
4. 웹뷰 설정: 웹뷰를 제대로 활용하기 위해서는 apply() 메서드를 사용하여 웹뷰에 필요한 설정을 진행해야 합니다. webViewClient와 webChromeClient 역시 활용해야 합니다. 아래는 예시 코드입니다:
Kotlin
webView.apply {
webViewClient = WebViewClientClass()
// 웹뷰에서 크롬 실행 가능 및 새 창 띄우기 설정
// webChromeClient = WebChromeClient()
}
AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.
5. 웹뷰에서 페이지 이동: canGoBack() 메서드와 canGoForward() 메서드를 사용하여 이전 페이지로 돌아가거나 앞 페이지로 이동할 수 있습니다.
이제 이 지침을 따라 코틀린 웹뷰에서 리액트 화면을 호출할 수 있습니다. 행운을 빕니다! 🚀
1. AndroidManifest.xml 인터넷 권한 설정
<manifest> 아래에 아래 코드를 추가한다.
<uses-permission android:name="android.permission.INTERNET" />
2. activity_main.xml 웹뷰 추가
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/progress1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
3. MainActivity.kt 웹뷰 호출 추가
package com.example.myapplication
import android.os.Bundle
import android.webkit.WebView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
val webView: WebView = findViewById(R.id.webView1)
webView.loadUrl("http://localhost:3000")
/* ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}*/
}
}
이렇게 수정하고 다시 프로젝트를 재시작하면 아래와 같은 에러가 발생한다.
Webpage not available
The webpage at http://localhost:3000/ could not loaded because:
net::ERR_CLEARTEXT_NOT_PERMITTED
AndroidManifest.xml <application>에 android:usesCleartextTraffic="true"를 추가한다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
tools:targetApi="31"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
이렇게 수정하고 다시 프로젝트를 재시작하면 아래와 같은 에러가 발생한다.
Webpage not available
The webpage at http://localhost:3000/ could not loaded because:
net::ERR_CONNECTION_REFUSED
MainActivity.kt 에 아래 부분을 수정한다.
//webView.loadUrl("http://localhost:3000")
webView.loadUrl("http://192.168.200.117:3000")
192.168.200.117 부분은 ipconfig /all 에서 할당받은 IP를 넣는다. 이렇게 수정하고 다시 프로젝트를 재시작하면 아래와 같은 에러가 발생한다.
You need to enable JavaScript to run this app.
MainActivity.kt 에 아래 부분을 추가한다.
webView.getSettings().setJavaScriptEnabled(true);
이제 정상적으로 웹뷰에서 http://localhost:3000/가 보인다.
최종 MainActivity.kt는 아래와 같다.
package com.example.myapplication
import android.annotation.SuppressLint
import android.os.Bundle
import android.webkit.WebView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
val webView: WebView = findViewById(R.id.webView1)
//webView.loadUrl("http://localhost:3000")
webView.loadUrl("http://192.168.200.117:3000")
webView.getSettings().setJavaScriptEnabled(true);
/* ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}*/
}
}