見出し画像

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");
        }
    }
}

とりあえず出来ました。
なんか画像が上手く表示できないですが。


今日はこんな感じですかね。
以上!!

この記事が気に入ったらサポートをしてみませんか?