Xamarin でとても簡単な android アプリを作る

前回の Hello, Android では、コードもアクティビティ(Windows アプリの ウィンドウのようなもの。アプリの画面。)も自動的に用意されていて、仕組みがよくわからなかったので、これらを自分で作ってみることにします。
とても簡単な例ということで、「ボタンを押したら文字を表示する」アプリを作ります。

Hello, Android の時と同じように、新規ソリューションを作成します。

まず画面(アクティビティ)を編集してみましょう。
左側のツリーから、[Resources] - [layout] - [Main.axml] をダブルクリックしてデザイナを開きます。
下の [コンテンツ] [ソース] のタブでソースの表示もできます。

デザイナの画面サイズを変更できます。
縦画面/横画面の切り替えもできます。
Android OS のバージョン違いによる、見栄えの違いも確認できます。
さて、自動的に作成されているボタンを削除します。
マウスでボタンを選択して、[Delete] キーを押せば削除出来ます。
消えました。
新しいボタンを配置します。
右側の [Toolbox] から [Button] をドラッグして配置します。
文字を表示させるために、[TextView] も配置します。
TextView を空きスペース一杯に広げます。
TextView を選択して [▼] 印をクリックすると空きスペース一杯に広がります。
[▼] 印が出ない時はもう一回クリックすると出てきます。(クリックするたびに、幅/高さの設定とマージンの設定が切り替わる。)
広がりました。

Button と TextView の id を確認しておきます。
右側の [プロパティ] - [Widget] の一番上に表示されています。これまでの手順通り進めてきたら、button1 と textView1 になっていると思います。自分のわかりやすいように変更しても良いです。

画面の編集はこれで終了。


ここから、ソースを編集して行きます。
まず、自動的に作られる MainActivity.cs です。


"MainActivity.cs"

namespace test0309
{
    [Activity (Label = "test0309", MainLauncher = true)]
    public class Activity1 : Activity
    {
        int count = 1;

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button> (Resource.Id.myButton);
            
            button.Click += delegate {
                button.Text = string.Format ("{0} clicks!", count++);
            };
        }
    }
}


元々あったボタンを削除しているので、このままビルドすると myButton が無くてエラーになりますので修正します。


"MainActivity.cs"

namespace test0309
{
    [Activity (Label = "test0309", MainLauncher = true)]
    public class Activity1 : Activity
    {
        int count = 1;

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            // Button button = FindViewById<Button> (Resource.Id.myButton);
            Button button = FindViewById<Button> (Resource.Id.button1);
            TextView textView = FindViewById<TextView> (Resource.Id.textView1);

            button.Click += delegate {
                textView.Text+=count.ToString()+"\r\n";
                button.Text = string.Format ("{0} clicks!", count++);
            };
        }
    }
}


太字の三行を追加しました。
リソース ID は、画面の編集の最後で確認した値を使用します。[Resources] - [Resource.designer.cs] ファイルで確認することもできます。

実行してみたところ。

このブログの人気の投稿

windowsで「インターネット接続の共有」の設定

月刊 I/O 記事リスト 1976~1989

X68000実機のROMを保存