1
1

More than 3 years have passed since last update.

眺めて覚える C# Xamarin Forms(7) 画面遷移

Posted at

Android用IoT Buttonの制作

コロナアイコンをダウンロードします。武漢病毒
image.png
これらのアイコンをボタン化します。
ファイル名を付け替えます。
image.png

新しいプロジェクトを作成します。

image.png

プロジェクトを構成します。

image.png

テンプレートを選択します。

image.png

アイコンをimgフォルダにドラッグします。

image.png

ドラックしたファイルをすべて選択して、プロパティを埋め込みリソースに変更します。

image.png

ボタンを表示できるかテスト

image.png
MainPage.xaml.csを開きます。

MyButtonクラスを作成します。

XamarinのButtonには、Tagオブジェクトがないためボタンがタッチされたときのイベントハンドラーを一括して扱えません。

MyButton.cs
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace Xamarin_7
{
    /// <summary>
    /// ボタンにTag機能を追加
    /// </summary>
    class MyButton:Xamarin.Forms.Button
    {
        public object Tag
        {
            get { return (object)GetValue(TagProperty); }
            set { SetValue(TagProperty, value); }
        }
        public static readonly BindableProperty TagProperty =
            BindableProperty.Create(nameof(Tag), typeof(object), typeof(MyButton), null);

    }
}

MainPage.xaml.csグリットレアウトにボタンを追加します。

MainPage.xaml.cs
sing Android.Widget;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Xamarin_7
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            var g = new Grid() { };
            var i = 0;var j = 0;
            for(var k = 0; k < 22; k++)
            {
                var b = new MyButton() { ImageSource = ImageSource.FromResource($"Xamarin_7.img.{k}.png"),Tag=k};
                b.Clicked +=(s, e)=>{ Bclick(s,e); };
                g.Children.Add(b, i, j);
                if (++i > 2) { i = 0;j++; }
            }
            Content = new Xamarin.Forms.ScrollView() { Orientation = ScrollOrientation.Vertical, Content = g };
        }
        /// <summary>
        /// ボタンイベントハンドラー
        /// </summary>
        /// <param name="s"></param>
        /// <param name="e"></param>
        private void Bclick(object s, EventArgs e)
        {
            var sx = s as MyButton;
            Toast.MakeText(Android.App.Application.Context,
                $"{sx.Tag}がタッチされた", ToastLength.Short).Show();
        }
        protected override bool OnBackButtonPressed()
        {
            App.Current.MainPage = new TabbedPage1();
            return true;
        }
    }
}

実行します。

image.png

ボタンをタッチすると

image.png

Toastで押されたボタン番号が表示されます。

画面遷移するためのページを作成します。

image.png

Page1.xaml.csに40個のテキストボタンを作成します。

Page1.xaml.cs
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Xamarin_7
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Page1 : ContentPage
    {
        public Page1()
        {
            InitializeComponent();
            var g = new Grid() { };
            var i = 0; var j = 0;
            for (var k = 0; k < 40; k++)
            {
                var b = new MyButton() { Text=$"Btn{k}", Tag = k };
                b.Clicked += (s, e) => { Bclick(s, e); };
                g.Children.Add(b, i, j);
                if (++i > 2) { i = 0; j++; }
            }
            Content = new Xamarin.Forms.ScrollView() { Orientation = ScrollOrientation.Vertical, Content = g };
        }

        private void Bclick(object s, EventArgs e)
        {
            var sx = s as MyButton;
            Toast.MakeText(Android.App.Application.Context,
                $"{sx.Tag}がタッチされた", ToastLength.Short).Show();
        }
        protected override bool OnBackButtonPressed()
        {
            App.Current.MainPage = new TabbedPage1();
            return true;
        }
    }
}

TabbedPage1.xamlを作成します

image.png

TabbedPage1.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Xamarin_7
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class TabbedPage1 : TabbedPage
    {
        public TabbedPage1()
        {
            InitializeComponent();
            this.Children.Clear();
            this.Children.Add(new MainPage() { Title = "Page0" });
            this.Children.Add(new Page1() { Title = "Page1" });
        }
    }
}

App.xaml.csを変更します。

image.png

MainPageをTabbedPagw1に変更します。

App.xaml.cs
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Xamarin_7
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            MainPage = new TabbedPage1(); //変更
        }

        protected override void OnStart()
        {
        }

        protected override void OnSleep()
        {
        }

        protected override void OnResume()
        {
        }
    }
}

実行結果

image.png

ついでにボタンをタッチしたら喋るようにするには、データを用意する。

speak.txt
科学研究者たちは新型コロナウイルスの起源に関する研究をいまも続けている。最近、南方医科大学公共衛生学院三級生物安全実験室のある研究論文では、新型コロナウイルスが発生した期間は2019年9月23日から2019年12月15日の間である可能性が高いと発表された
新型コロナウイルスと遺伝子配列が最も似ているコウモリが持つコロナウイルス「RaTG13」には時間的な進化関係が存在せず、新型コロナウイルスはRaTG13が進化したものではない可能性が高いことがわかった。
新型コロナウイルスに感染した英国のジョンソン首相が27日、公務に復帰する。先月末に感染が発覚し、一時は集中治療室に入るほど病状が悪化したが、12日に退院。ロンドン郊外の首相別邸で療養していた。新型コロナ感染による国内の死者が2万人を超えるなか、外出制限や商店の閉鎖といった措置の緩和を求める声が強まっており、復帰早々、様々な判断が待ち受けている。
「咳エチケット」は、感染症を他人に感染させないために、個人が咳・くしゃみをする際に、マスクやティッシュ・ハンカチ、袖を使って、口や鼻をおさえることです。
生肉および生肉製品の取り扱い・調理の際は、その他の病原体も生残している可能性があることを考慮し、衛生規則に従って細心の注意を払うべきである。
火を通した食べ物をとろう。
マスクをしよう。
防護服を用意しよう
未定義
未定義
未定義
未定義
未定義
未定義
未定義
未定義
未定義
未定義
未定義
未定義
未定義

喋らせるためのクラスの作成

プラグインの導入
Xam.Plugins.TextToSpeech

Text2Speech.cs
using Plugin.TextToSpeech;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace Xamarin_7
{
    class Text2Speech
    {
        public List<string> Data { get; set; }
        public Text2Speech()
        {
            Data = ReadTxt();
        }
        /// <summary>
        /// データを読み込む
        /// </summary>
        /// <param name="filename">リソース ファイル名</param>
        /// <returns></returns>
        public  List<string> ReadTxt(string filename = "Xamarin_7.Data.speak.txt")
        {

            var assembly = Assembly.GetExecutingAssembly();
            using (Stream stream = assembly.GetManifestResourceStream(filename))
            using (StreamReader reader = new StreamReader(stream))
            {
                var txt = reader.ReadToEnd();
                var lines = txt.Split('\n');
                var lst = new List<string>();
                lst.AddRange(lines);               
                return lst;
            }
        }
        /// <summary>
        /// 喋る
        /// </summary>
        /// <param name="n">データ番号</param>
        public void Speak(Int32 n)
        {
            CrossTextToSpeech.Current.Speak(Data[n]);
        }
    }
}

MainPage.csにしゃべらせるスクリプトを追加。

MainPage.xaml.cs
using Android.Widget;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Xamarin_7
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        Text2Speech Sp =new Text2Speech(); //喋らせる準備
        public MainPage()
        {
            InitializeComponent();
            var g = new Grid() { };
            var i = 0;var j = 0;
            for(var k = 0; k < 22; k++)
            {
                var b = new MyButton() { ImageSource = ImageSource.FromResource($"Xamarin_7.img.{k}.png"),Tag=k};
                b.Clicked +=(s, e)=>{ Bclick(s,e); };
                g.Children.Add(b, i, j);
                if (++i > 2) { i = 0;j++; }
            }
            Content = new Xamarin.Forms.ScrollView() { Orientation = ScrollOrientation.Vertical, Content = g };
        }
        /// <summary>
        /// ボタンイベントハンドラー
        /// </summary>
        /// <param name="s"></param>
        /// <param name="e"></param>
        private void Bclick(object s, EventArgs e)
        {
            var sx = s as MyButton;
            Toast.MakeText(Android.App.Application.Context,
                $"{sx.Tag}がタッチされた", ToastLength.Short).Show();
            int n =(int) sx.Tag;
            Sp.Speak(n); //喋らせる
        }
        protected override bool OnBackButtonPressed()
        {
            App.Current.MainPage = new TabbedPage1();
            return true;
        }
    }
}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1