![見出し画像](https://assets.st-note.com/production/uploads/images/102162294/rectangle_large_type_2_900c95b6b3afd5d518cd0c3c4ca3f8f4.png?width=1200)
Webサイトをスマホアプリで見るプログラム
スマホアプリを作る過程で、「UWP」の本読んでたんですけど、ここに「WebView」使えばwebサイトをアプリに簡単に落とし込める的な事が書かれてました。
しかし、確かに「WebView」を使うのは手っ取り早いのですが、これには脆弱性があるらしく、現在は「InAppBrowser」が推奨とのこと。
が、私にはよく分からなかったので「webview」でやることにしました。
という事でやってみました。
ちなみに開発環境は「Visual Studio2022」です。
まずXMLはこんな感じ
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<LinearLayout
android:id="@+id/myLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>
<android.webkit.WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/webView1"
/>
</RelativeLayout>
次にプログラム部分(C#です)
using Android.Webkit;
namespace WebSiteApps
{
[Activity(Label = "@string/app_name", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle? savedInstanceState)
{
//いつものおまじない
base.OnCreate(savedInstanceState);
//できなかった
//var webview = FindViewById<WebView>(Resource.id.)
//この方法でインスタンス化することが可能
WebView myWebView = new(this);
// WebViewをレイアウトに追加
SetContentView(Resource.Layout.activity_main);
LinearLayout? layout = FindViewById<LinearLayout>(Resource.Id.myLayout);
//nullの時の処理。とりあえず書いとく。
if (layout != null)
{
layout.AddView(myWebView);
}
else
{
//なんかの処理
}
//URLを設定。今回は私のURLに飛ぶようにする。
myWebView.LoadUrl("https://note.com/yayoiisyayoi");
}
}
}
とりあえず出来ました。
なんか画像が上手く表示できないですが。
![](https://assets.st-note.com/img/1680681528419-GI59x32ecy.png?width=1200)
今日はこんな感じですかね。
以上!!
この記事が気に入ったらサポートをしてみませんか?