Xamarin-quick-guide
Xamarin-インストール
Xamarinは.NET Framework上に構築されています。 複数のプラットフォームで簡単に実行できるアプリを作成できます。 このチュートリアルでは、Xamarinを使用してネイティブiOS、Android、およびWindowsアプリを配信する方法を説明します。
XamarinをWindowsおよびMacシステムにインストールする方法についての議論からチュートリアルを始めましょう。
システム要求
Windows
- 2GB以上のRAMを搭載し、Windows 7以降を実行しているコンピューター_(Windows 8-10を強くお勧めします)_
- Visual Studio 2012 Professional以降
- Xamarin for Visual Studio
Mac
- OS X Yosemite(10.10)以降を実行しているMacコンピューター
- Xamarin iOS SDK
- AppleのXcode(7+)IDEおよびiOS SDK
- Xamarin Studio
Windowsへのインストール
[[1]] SDKとJava SDKがインストールされていることを確認してください。
ダウンロードしたインストーラーを実行して、インストールプロセスを開始します-
- Xamarinライセンス契約画面が表示されます。 [次へ]ボタンをクリックして、契約に同意します。
- インストーラーは、不足しているコンポーネントを検索し、それらをダウンロードしてインストールするように促します。
- Xamarinのインストールが完了したら、[閉じる]ボタンをクリックして終了し、Xamarinの使用を開始する準備をします。
Macへのインストール
- MacシステムにXamarin Studioインストーラーをダウンロードします。
- ダウンロードしたXamarinインストーラーを実行し、インストールウィザードの手順に従います。
- インストールが完了したら、システムでXamarinの使用を開始できます。
Xamarin-最初のアプリケーション
この章では、Xamarinを使用して小さなAndroidアプリケーションを作成する方法を説明します。
こんにちは、Xamarin! 応用
まず、Visual Studioの新しいインスタンスを起動し、[ファイル]→[新規]→[プロジェクト]に移動します。
表示されるメニューダイアログボックスで、*テンプレート→Visual C#→Android→Blank App(Android)*に移動します。
アプリケーションに適切な名前を付けます。 この例では、「helloWorld」という名前を付け、指定されたデフォルトの場所に保存します。 次に、ロードする新しい“ helloXamarin” *プロジェクトの[OK]ボタンをクリックします。
- ソリューション*で、*リソース→レイアウト→Main.axml *ファイルを開きます。 デザインビューから切り替えて、*ソース*ファイルに移動し、次のコード行を入力してアプリをビルドします。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:background = "#d3d3d3"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<TextView
android:text = "@string/HelloXamarin"
android:textAppearance = "?android:attr/textAppearanceLarge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/textView2"
android:textColor = "@android:color/black"/>
</LinearLayout>
上記のコードでは、新しいAndroid textview を作成しました。 次に、フォルダーの値を開き、 Strings.xml をダブルクリックして開きます。 ここでは、上で作成した*ボタン*に関する情報と値を保存します。
<?xml version = "1.0" encoding = "utf-8"?>
<resources>
<string name = "HelloXamarin">Hello World, I am Xamarin!</string>
<string name = "ApplicationName">helloWorld</string>
</resources>
*MainActivity.cs* ファイルを開き、既存のコードを次のコード行に置き換えます。
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace HelloXamarin {
public class MainActivity : Activity {
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
}
}
}
アプリケーションを保存します。 ビルドして実行し、作成したアプリをAndroidエミュレーターで表示します。
Androidエミュレーターがない場合は、次のセクションに記載されている手順に従って作成してください。
Androidエミュレーターのセットアップ
Visual Studioメニューで、[ツール]→[Android]→[Android Emulator Manager] *に移動します。 表示されるポップアップウィンドウで、[作成]ボタンをクリックします。 次の画面が表示されます。
上記の画面で、必要な* AVD名*を指定します。 ディスプレイに適した*デバイス*(Nexus 4インチディスプレイなど)を選択します。 *対象プラットフォーム*を選択します。 アプリがすべてのAndroidプラットフォームで動作することを確認するために、API 10 Android 2.3(Gingerbread)などの最小ターゲットプラットフォームでテストすることを常にお勧めします。
残りのフィールドに入力し、[OK]ボタンをクリックします。 これで、エミュレータの準備ができました。 既存のAndroid仮想デバイスのリストから選択し、[開始]をクリックして起動できます。
HelloXamarinアプリの変更
このセクションでは、プロジェクトを変更し、クリックするとテキストを表示するボタンを作成します。 main.axml を開き、ソースビュー*に切り替えます。 作成した *textview の後に、次のようにボタンを追加します。
<Button
android:id = "@+id/MyButton"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "@string/ButtonClick"/>
ボタンを追加すると、完全なコードは次のようになります-
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<TextView
android:text = "@string/HelloXamarin"
android:textAppearance = "?android:attr/textAppearanceLarge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/textView2"/>
<Button
android:id = "@+id/MyButton"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "@string/ButtonClick"/>
</LinearLayout>
次に、ボタンの値を strings.xml ファイルに登録します。
<string name = "ButtonClick">Click Me!</string>
*strings.xml* ファイルにボタンを追加した後、次のコードに示すように、ボタンがクリックされたときにボタンのアクションを追加するために *MainActivity.cs* ファイルを開きます。
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace HelloXamarin {
[Activity(Label = "HelloXamarin", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity {
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate { button.Text = "Hello world I am your first App"; };
}
}
}
次に、アプリケーションをビルドして実行します。
ボタンをクリックすると、次の出力が得られます-
Xamarin-アプリケーションマニフェスト
すべてのAndroidアプリには、一般に AndroidManifest.xml と呼ばれる*マニフェストファイル*があります。 マニフェストファイルには、アプリを正常に実行するために必要なAndroidプラットフォームに関するすべてが含まれています。
ここでは、マニフェストファイルの重要な機能の一部をリストしました-
- アプリケーションに必要な*最小APIレベル*を宣言します。
- アプリケーションに必要な権限(カメラ、場所など)を宣言します
- アプリケーションが使用または要求するハードウェアおよびソフトウェア機能への許可を与えます。
- アプリケーションをリンクする必要があるライブラリがリストされます。
次のスクリーンショットは、マニフェストファイルを示しています。
アプリケーション名-アプリのタイトルを指します
パッケージ名-アプリを識別するために使用される一意の名前です。
アプリケーションアイコン-アプリのAndroidホーム画面に表示されるアイコンです。
バージョン番号-アプリのあるバージョンが別のバージョンよりも新しいことを示すために使用される単一の番号です。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1" >
バージョン名-これは、ユーザーがアプリの設定とGoogle PlayStoreで見ることができるアプリのユーザーフレンドリーなバージョン文字列です。 次のコードは、バージョン名の例を示しています。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionName="1.0.0">
最小Androidバージョン-アプリケーションがサポートする最も低いAndroidバージョンのプラットフォームです。
<uses-sdk android:minSdkVersion="16"/>
上記の例では、Androidの最小バージョンはAPIレベル16で、一般に JELLY BEAN と呼ばれています。
ターゲットAndroidバージョン-アプリがコンパイルされるAndroidバージョンです。
Xamarin-Androidリソース
新しいAndroidプロジェクトが作成されると、デフォルトでプロジェクトに追加されるファイルがいくつかあります。 これらのデフォルトのプロジェクトファイルとフォルダーを Android Resources と呼びます。 次のスクリーンショットをご覧ください。
デフォルトのAndroidリソースには次のものが含まれます-
- * AndroidManifest.xmlファイル*-Androidアプリケーションに関する情報、たとえば、アプリケーション名、権限などが含まれています。
- リソースフォルダ-リソースは画像、レイアウト、文字列などです。 Androidのリソースシステム経由で読み込むことができます。
- Resources/drawable folder -アプリケーションで使用するすべての画像を保存します。
- Resources/layout folder -Androidがユーザーインターフェイスを構築するために使用するすべてのAndroid XMLファイル(.axml)が含まれています。
- * Resources/valuesフォルダー*-アプリケーション全体の文字列(およびその他のタイプ)のキーと値のペアを宣言するXMLファイルが含まれています。 これは、Androidで複数言語のローカライズが通常設定される方法です。
- Resources.designer.cs -このファイルは、投影されるAndroidの作成時に自動的に作成され、Androidリソースを参照する一意の識別子が含まれます。
- * MainActivity.csファイル*-これは、Androidアプリケーションの最初のアクティビティであり、メインアプリケーションアクションの起動元です。
リソースファイルは、 resources.designer.cs ファイルに保存されている*一意のID を介してプログラムでアクセスできます。 IDは、 *Resource というクラスの下に含まれています。 プロジェクトに追加されたリソースは、*リソースクラス*内で自動的に生成されます。
次のコードは、7つの画像を含むgridviewプロジェクトを作成する方法を示しています-
namespace HelloGridView {
[System.CodeDom.Compiler.GeneratedCodeAttribute
("Xamarin.Android.Build.Tas ks",
"1.0.0.0")]
public partial class Resource {
static Resource() {
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public static void UpdateIdValues() {}
public partial class Attribute {
static Attribute() {
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute() {}
}
public partial class Drawable {
//aapt resource value: 0x7f020000
public const int Icon = 2130837504;
//aapt resource value: 0x7f020001
public const int img1 = 2130837505;
//aapt resource value: 0x7f020002
public const int img2 = 2130837506;
//aapt resource value: 0x7f020003
public const int img3 = 2130837507;
//aapt resource value: 0x7f020004
public const int img4 = 2130837508;
//aapt resource value: 0x7f020005
public const int img5 = 2130837509;
//aapt resource value: 0x7f020006
public const int img6 = 2130837510;
//aapt resource value: 0x7f020007
public const int img7 = 2130837511;
static Drawable() {
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Drawable() {}
}
public partial class Id {
//aapt resource value: 0x7f050000
public const int gridview = 2131034112;
static Id() {
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Id() {}
}
public partial class Layout {
//aapt resource value: 0x7f030000
public const int Main = 2130903040;
static Layout() {
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Layout() {}
}
public partial class String {
//aapt resource value: 0x7f040001
public const int ApplicationName = 2130968577;
//aapt resource value: 0x7f040000
public const int Hello = 2130968576;
static String() {
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String() {}
}
}
}
上記のコードから、7つの画像は drawable と呼ばれるクラスで参照されます。 これらの画像はプログラムで追加されます。 ユーザーがプロジェクトに別の画像を追加すると、その画像は drawable クラスにも追加されます。 プロジェクトに含まれる gridview も追加され、独自のクラスに保存されます。 * resourcesフォルダ*に含まれる各アイテムは自動的に生成され、クラスに保存されます。
Xamarin-Androidアクティビティライフサイクル
ユーザーがAndroidアプリをナビゲートすると、一連のイベントが発生します。 たとえば、ユーザーがアプリ(Facebookアプリなど)を起動すると、アプリが起動し、フォアグラウンドで* onCreate()→onStart()→onResume()*に表示されます。
別のアクティビティが開始された場合、たとえば電話がかかってきた場合、Facebookアプリはバックグラウンドになり、通話はフォアグラウンドになります。 現在、2つのプロセスが実行されています。
onPause() --- > onStop()
通話が終了すると、Facebookアプリはフォアグラウンドに戻ります。 3つのメソッドが呼び出されます。
onRestart() --- > onStart() --- > onResume()
Androidアクティビティには7つのライフサイクルプロセスがあります。 彼らが含まれます-
- onCreate -アクティビティが最初に作成されたときに呼び出されます。
- onStart -アクティビティが開始され、ユーザーに表示されるときに呼び出されます。
- onResume -アクティビティがユーザーとの対話を開始すると呼び出されます。 この段階でユーザー入力が行われます。
- onPause -アクティビティがバックグラウンドで実行されているが、まだ強制終了されていない場合に呼び出されます。
- onStop -アクティビティがユーザーに表示されなくなったときに呼び出されます。
- onRestart -アクティビティが停止した後、再開する前に呼び出されます。 通常、ユーザーが停止した前のアクティビティに戻るときに呼び出されます。
- onDestroy -これは、アクティビティがメモリから削除される前の最後の呼び出しです。
次の図は、Androidアクティビティライフサイクルを示しています-
Xamarin-権限
Androidでは、デフォルトで、ユーザーまたはオペレーティングシステムに影響を与える操作を実行する権限を持つアプリケーションはありません。 アプリがタスクを実行するには、アクセス許可を宣言する必要があります。 Androidシステムから許可が与えられるまで、アプリはタスクを実行できません。 この許可のメカニズムにより、ユーザーの同意なしに、アプリケーションが希望どおりに実行できなくなります。
権限は AndroidManifest.xml ファイルに記録されます。 アクセス許可を追加するには、プロパティをダブルクリックしてから、Android Man * Required permissions *に移動します。 追加する適切な権限を確認します。
カメラ-デバイスのカメラへのアクセス許可を提供します。
<uses-permission android:name="android.permission.CAMERA"/>
インターネット-ネットワークリソースへのアクセスを提供します。
<uses-permission android:name="android.permission.INTERNET"/>
*ReadContacts* -デバイス上の連絡先を読み取るためのアクセスを提供します。
<uses-permission android:name="android.permission.READ_CONTACTS"/>
*ReadExternalStorage* -外部ストレージのデータを読み取り、保存するためのアクセスを提供します。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
カレンダー-ユーザーのデバイスおよびイベントのカレンダーへのアプリアクセスを許可します。 この許可は、所有者の気付かないうちにゲストにメールを送信する機能をアプリに付与するため、危険です。 この権限を追加するための構文は以下のとおりです-
<uses-permission android:name="android.permission-group.CALENADAR"/>
*SMS* -この権限を持つアプリは、デバイスメッセージングサービスを使用する機能を備えています。 SMSおよびMMSメッセージの読み取り、書き込み、および編集が含まれます。 構文は次のとおりです。
<uses-permission android:name="android.permission-group.SMS"/>
場所-この権限を持つアプリは、GPSネットワークを使用してデバイスの場所にアクセスできます。
<uses-permission android:name="android.permission-group.LOCATION"/>
*Bluetooth* -この権限を持つアプリは、他のBluetooth対応デバイスとワイヤレスでデータファイルを交換できます。
<uses-permission android:name="android.permission.BLUETOOTH"/>
Xamarin-アプリGUIの構築
TextView
TextViewは、Androidウィジェットの非常に重要なコンポーネントです。 主に、Android画面にテキストを表示するために使用されます。
テキストビューを作成するには、単に main.axml を開き、線形レイアウトタグの間に次のコードを追加します。
<TextView
android:text = "Hello I am a text View"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/textview1"/>
ボタン
ボタンは、クリックされたときにイベントをトリガーするために使用されるコントロールです。 Main.axml ファイルの下に、次のコードを入力してボタンを作成します。
<Button
android:id = "@+id/MyButton"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "@string/Hello"/>
*Resources \ Values \ Strings.xml* を開き、<resources>タグの間に次のコード行を入力します。
<string name="Hello">Click Me!</string>
上記のコードは、作成したボタンの値を提供します。 次に、 MainActivity.cs を開き、ボタンがクリックされたときに実行されるアクションを作成します。 base.OnCreate (バンドル)メソッドの下に次のコードを入力します。
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate { button.Text = "You clicked me"; };
上記のコードでは、ユーザーがボタンをクリックすると「You Clicked Me」と表示されます。
*FindViewById <<->* このメソッドは、識別されたビューのIDを検索します。 .axmlレイアウトファイルでIDを検索します。
チェックボックス
チェックボックスは、オプションのグループから複数のオプションを選択する場合に使用されます。 この例では、チェックボックスを作成します。チェックボックスを選択すると、チェックされたことを示すメッセージが表示されます。
まず、プロジェクトで Main.axml ファイルを開き、次のコード行を入力してチェックボックスを作成します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:background = "#d3d3d3"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<CheckBox
android:text = "CheckBox"
android:padding = "25dp"
android:layout_width = "300dp"
android:layout_height = "wrap_content"
android:id = "@+id/checkBox1"
android:textColor = "@android:color/black"
android:background = "@android:color/holo_blue_dark"/>
</LinearLayout>
次に、 MainActivity.cs に移動して機能コードを追加します。
CheckBox checkMe = FindViewById<CheckBox>(Resource.Id.checkBox1);
checkMe.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => {
CheckBox check = (CheckBox)sender;
if(check.Checked) {
check.Text = "Checkbox has been checked";
} else {
check.Text = "Checkbox has not been checked";
}
};
上記のコードから、最初に findViewById を使用してチェックボックスを見つけます。 次に、チェックボックスのハンドラーメソッドを作成し、ハンドラーで、選択した結果に応じてメッセージを表示するif elseステートメントを作成します。
*CompoundButton.CheckedChangeEventArgs* →このメソッドは、チェックボックスの状態が変化したときにイベントを発生させます。
プログレスバー
進行状況バーは、操作の進行状況を示すために使用されるコントロールです。 プログレスバーを追加するには、 Main.axml ファイルに次のコード行を追加します。
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/progressBar1"/>
次に、 MainActivity.cs に進み、進行状況バーの値を設定します。
ProgressBar pb = FindViewById<ProgressBar>(Resource.Id.progressBar1);
pb.Progress = 35;
上記のコードでは、値が35のプログレスバーを作成しました。
ラジオボタン
これは、ユーザーが一連のオプションから1つを選択できるAndroidウィジェットです。 このセクションでは、チェックされたラジオボタンを取得する車のリストを含むラジオグループを作成します。
まず、次のコードに示すように、ラジオグループと textview を追加します-
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:background = "@android:color/darker_gray"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<TextView
android:text = "What is your favourite Car"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/textView1"
android:textColor = "@android:color/black"/>
<RadioGroup
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/radioGroup1"
android:backgroundTint = "#a52a2aff"
android:background = "@android:color/holo_green_dark">
<RadioButton
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Ferrari"
android:id = "@+id/radioFerrari"/>
<RadioButton
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Mercedes"
android:id = "@+id/radioMercedes"/>
<RadioButton
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Lamborghini"
android:id = "@+id/radioLamborghini"/>
<RadioButton
android:text = "Audi"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/radioAudi"/>
</RadioGroup>
</LinearLayout>
アクションを実行するには、ラジオボタンがクリックされたときにアクティビティを追加します。 MainActivity.cs に移動し、以下に示すように新しいイベントハンドラーを作成します。
private void onClickRadioButton(object sender, EventArgs e) {
RadioButton cars = (RadioButton)sender;
Toast.MakeText(this, cars.Text, ToastLength.Short).Show
();
}
- Toast.MakeText()→これは、メッセージ/出力を小さなポップアップで表示するために使用されるビューメソッドです。 * SetContentView()*の直後の OnCreate()*メソッドの下部に、次のコードを追加します。 これにより、各ラジオボタンがキャプチャされ、作成したイベントハンドラーに追加されます。
RadioButton radio_Ferrari = FindViewById<RadioButton>
(Resource.Id.radioFerrari);
RadioButton radio_Mercedes = FindViewById<RadioButton>
(Resource.Id.radioMercedes);
RadioButton radio_Lambo = FindViewById<RadioButton>
(Resource.Id.radioLamborghini);
RadioButton radio_Audi = FindViewById<RadioButton>
(Resource.Id.radioAudi);
radio_Ferrari.Click += onClickRadioButton;
radio_Mercedes.Click += onClickRadioButton;
radio_Lambo.Click += onClickRadioButton;
radio_Audi.Click += onClickRadioButton;
次に、アプリケーションを実行します。 出力として次の画面を表示する必要があります-
トグルボタン
トグルボタンは、2つの状態を切り替えるために使用されます。たとえば、オンとオフを切り替えることができます。 Resources \ layout \ Main.axml を開き、次のコード行を追加してトグルボタンを作成します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:background = "#d3d3d3"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<ToggleButton
android:id = "@+id/togglebutton"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textOn = "Torch ON"
android:textOff = "Torch OFF"
android:textColor = "@android:color/black"/>
</LinearLayout>
クリックされたときにトグルバーにアクションを追加できます。 MainActivity.cs を開き、* OnCreate()*メソッドクラスの後に次のコード行を追加します。
ToggleButton togglebutton = FindViewById<ToggleButton> (Resource.Id.togglebutton);
togglebutton.Click += (o, e) => {
if (togglebutton.Checked)
Toast.MakeText(this, "Torch is ON", ToastLength.Short).Show ();
else
Toast.MakeText(this, "Torch is OFF",
ToastLength.Short).Show();
};
さて、アプリを実行すると、次の出力が表示されるはずです-
評価バー
評価バーは星で構成されたフォーム要素であり、アプリのユーザーはこれを使用して、提供したものを評価できます。 Main.axml ファイルで、5つ星の新しい評価バーを作成します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:background = "#d3d3d3"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<RatingBar
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/ratingBar1"
android:numStars = "5"
android:stepSize = "1.0"/>
</LinearLayout>
アプリを実行すると、次の出力が表示されます-
オートコンプリートテキストビュー
これは、ユーザーが入力している間に完全な候補を表示するテキストビューです。 ユーザーの名前のリストと、クリックすると選択した名前が表示されるボタンを含むオートコンプリートテキストビューを作成します。
*Main.axml* を開き、次のコードを記述します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:background = "#d3d3d3"
android:layout_height = "fill_parent">
<TextView
android:text = "Enter Name"
android:textAppearance = "?android:attr/textAppearanceMedium"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:id = "@+id/textView1"
android:padding = "5dp"
android:textColor = "@android:color/black"/>
<AutoCompleteTextView
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:id = "@+id/autoComplete1"
android:textColor = "@android:color/black"/>
<Button
android:text = "Submit"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:id = "@+id/btn_Submit"
android:background="@android:color/holo_green_dark"/>
</LinearLayout>
上記のコードは、入力用のTextView、候補を表示するための AutoCompleteTextView 、およびTextViewから入力された名前を表示するボタンを生成します。 MainActivity.cs に移動して機能を追加します。
以下に示すように、新しいイベントハンドラーメソッドを作成します。
protected void ClickedBtnSubmit(object sender, System.EventArgs e){
if (autoComplete1.Text != ""){
Toast.MakeText(this, "The Name Entered ="
+ autoComplete1.Text, ToastLength.Short).Show();
} else {
Toast.MakeText(this, "Enter a Name!", ToastLength.Short).Show();
}
}
作成されたハンドラーは、オートコンプリートテキストビューが空かどうかを確認します。 空でない場合は、選択したオートコンプリートテキストが表示されます。 * OnCreate()*クラス内に次のコードを入力します。
autoComplete1 = FindViewById<AutoCompleteTextView>(Resource.Id.autoComplete1);
btn_Submit = FindViewById<Button>(Resource.Id.btn_Submit);
var names = new string[] { "John", "Peter", "Jane", "Britney" };
ArrayAdapter adapter = new ArrayAdapter<string>(this,
Android.Resource.Layout.SimpleSpinnerItem, names);
autoComplete1.Adapter = adapter;
btn_Submit.Click += ClickedBtnSubmit;
*ArrayAdapter* -これは、リストコレクションからデータ項目を読み取り、それらをビューとして返すか、画面に表示するコレクションハンドラーです。
これで、アプリケーションを実行すると、次の出力が表示されます。
Xamarin-メニュー
ポップアップメニュー
ポップアップメニューとは、ビューに添付されているメニューのことです。 *ショートカットメニュー*とも呼ばれます。 Androidアプリにポップアップメニューを追加する方法を見てみましょう。
新しいプロジェクトを作成し、 popUpMenu App と呼びます。 Main.axml を開き、ポップアップメニューを表示するために使用するボタンを作成します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:background = "#d3d3d3"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<Button
android:id = "@+id/popupButton"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "Show popup menu"
android:background = "@android:color/holo_green_dark"
android:textColor = "@android:color/black"/>
</LinearLayout>
*Resources* フォルダーの下に新しいフォルダーを作成し、 *Menu* と呼びます。 Menuフォルダー内に、 *popMenu.xml* という新しいxmlファイルを追加します。
*popMenu.xml* で、次のメニュー項目を追加します。
<?xml version = "1.0" encoding="utf-8"?>
<menu xmlns:android = "http://schemas.android.com/apk/res/android">
<item
android:id = "@+id/file_settings"
android:icon = "@drawable/img_settings"
android:title = "Settings"
android:showAsAction = "ifRoom">
<item
android:id = "@+id/new_game1"
android:icon = "@drawable/imgNew"
android:title = "New File Settings"/>
<item
android:id = "@+id/help"
android:icon = "@drawable/img_help"
android:title = "Help"/>
<item
android:id = "@+id/about_app"
android:icon = "@drawable/img_help"
android:title = "About app"/>
</item>
</menu>
メニュー項目を追加したら、 mainActivity.cs に移動して、ボタンのクリック時にポップアップメニューを表示します。
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button showPopupMenu = FindViewById<Button>(Resource.Id.popupButton);
showPopupMenu.Click += (s, arg) => {
PopupMenu menu = new PopupMenu(this, showPopupMenu);
menu.Inflate(Resource.Menu.popMenu);
menu.Show();
};
}
次に、アプリケーションをビルドして実行します。 それは次の出力を生成する必要があります-
オプションメニュー
オプションメニューは、アプリの主要なメニューのコレクションであり、主に設定の保存、検索などに使用されます。 ここでは、3つの項目、つまり*新しいファイル設定、ヘルプ、およびアプリについて*を含む設定のメニューを作成します。
オプションメニューを作成するには、リソースフォルダーに新しいXMLレイアウトファイルを作成する必要があります。 まず、新しいXMLファイルを追加します。 *レイアウトフォルダー*を右クリックし、*追加→新規アイテム→Visual C#→XMLファイル*に移動します。
レイアウトファイル*に適切な名前を選択します。 この例では、ファイル *myMenu.xml を呼び出します。
*myMenu.xml* 内で、新しいメニューを作成し、内部にアイテムを追加します。 次のコードは、その方法を示しています。
<?xml version = "1.0" encoding = "utf-8"?>
<menu xmlns:android = "http://schemas.android.com/apk/res/android">
<item
android:id = "@+id/file_settings"
android:icon = "@drawable/img_settings"
android:title = "Settings"
android:showAsAction = "ifRoom">
<menu>
<item
android:id = "@+id/new_game1"
android:icon = "@drawable/imgNew"
android:title = "New File Settings"/>
<item
android:id = "@+id/help"
android:icon = "@drawable/img_help"
android:title = "Help"/>
<item
android:id = "@+id/about_app"
android:icon = "@drawable/img_help"
android:title = "About app"/>
</menu>
</item>
</menu>
次に、 MainActivity.cs に移動し、* onOptionsMenu()*のオーバーライドクラスを作成します。
public override bool OnCreateOptionsMenu(IMenu menu) {
MenuInflater.Inflate(Resource.Menu.myMenu, menu);
return base.OnPrepareOptionsMenu(menu);
}
次に、設定メニュー*が選択されたときに応答するアクションを作成します。 これを行うには、 OnOptionsItemSelected()*メニューの別のオーバーライドクラスを作成します。
public override bool OnOptionsItemSelected(IMenuItem item) {
if (item.ItemId == Resource.Id.file_settings) {
//do something here...
return true;
}
return base.OnOptionsItemSelected(item);
}
最終的な完全なコードは次のようになります-
namespace optionsMenuApp {
[Activity(Label = "options Menu", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity {
public override bool OnCreateOptionsMenu(IMenu menu) {
MenuInflater.Inflate(Resource.Menu.myMenu, menu);
return base.OnPrepareOptionsMenu(menu);
}
public override bool OnOptionsItemSelected(IMenuItem item) {
if (item.ItemId == Resource.Id.file_settings) {
//do something here...
return true;
}
return base.OnOptionsItemSelected(item);
}
}
}
次に、アプリケーションをビルドして実行します。 それは次の出力を生成する必要があります-
Xamarin-レイアウト
線形レイアウト
線形レイアウトでは、コンテンツは水平または垂直に配置されます。
線形レイアウト─水平
このレイアウトのコンテンツは水平に配置されます。 このデモでは、3つのボタンを作成し、線形レイアウトで水平に配置します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "horizontal"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:background = "#d3d3d3"
android:minWidth="25px"
android:minHeight="25px">
<Button
android:id="@+id/MyButton1"
android:layout_width="wrap_content"
android:layout_margin="10dp"
android:layout_height="wrap_content"
android:text="Button 1"
android:background="@android:color/holo_green_dark"/>
<Button
android:id="@+id/MyButton2"
android:layout_width="wrap_content"
android:layout_margin="10dp"
android:layout_height="wrap_content"
android:text="Button 2"
android:background="@android:color/holo_green_dark"/>
<Button
android:id="@+id/MyButton3"
android:layout_width="wrap_content"
android:layout_margin="10dp"
android:layout_height="wrap_content"
android:text="Button 3"
android:background="@android:color/holo_green_dark"/>
</LinearLayout>
結果の出力は以下のようになります-
線形レイアウト─垂直
このタイプのレイアウトは、子ビューを垂直に配置します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:background = "#d3d3d3"
android:minWidth = "25px"
android:minHeight = "25px">
<Button
android:id = "@+id/MyButton1"
android:layout_width = "fill_parent"
android:layout_margin = "10dp"
android:layout_height = "wrap_content"
android:text = "Button 1"
android:background = "@android:color/holo_green_dark"/>
<Button
android:id = "@+id/MyButton2"
android:layout_width = "fill_parent"
android:layout_margin = "10dp"
android:layout_height = "wrap_content"
android:text = "Button 2"
android:background = "@android:color/holo_green_dark"/>
<Button
android:id = "@+id/MyButton3"
android:layout_width = "fill_parent"
android:layout_margin = "10dp"
android:layout_height = "wrap_content"
android:text="Button 3"
android:background = "@android:color/holo_green_dark"/>
</LinearLayout>
その結果の出力は次のとおりです-
相対レイアウト
このビューでは、子ビューの位置は、その親または兄弟ビューに対して相対的です。 次の例では、3つのEditTextビューとボタンを作成し、それらを相対的に配置します。
新しいプロジェクトを作成し、それを relative layout app と呼びます。 main.axml を開き、次のコードを追加します。
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:paddingLeft = "16dp"
android:background = "#d3d3d3"
android:paddingRight = "16dp">
<EditText
android:id = "@+id/name"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:hint = "First Name"
android:textColorHint = "@android:color/background_dark"
android:textColor = "@android:color/background_dark"/>
<EditText
android:id = "@+id/lastName"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:hint = "Last Name"
android:layout_below = "@id/name"
android:textColorHint = "@android:color/background_dark"
android:textColor = "@android:color/background_dark"
android:layout_alignParentLeft = "true"
android:layout_toLeftOf = "@+id/age"/>
<EditText
android:id = "@id/age"
android:layout_width = "80dp"
android:layout_height = "wrap_content"
android:layout_below = "@id/name"
android:hint = "Age"
android:textColorHint = "@android:color/background_dark"
android:textColor = "@android:color/background_dark"
android:layout_alignParentRight = "true"/>
<Button
android:layout_width = "85dp"
android:layout_height = "wrap_content"
android:layout_below = "@id/age"
android:layout_alignParentRight = "true"
android:text = "Submit"
android:background = "@android:color/holo_green_dark"/>
</RelativeLayout>
このコードで使用した重要なパラメータは次のとおりです-
- android:layout_below -子ビュー要素をその親の下に揃えます。
- android:layout_alignParentLeft -親要素を左に揃えます。
- android:layout_toLeftOf -このプロパティは、要素を別の要素の左に揃えます。
- android:layout_alignParentRight -親を右に揃えます。
今すぐアプリをビルドして実行すると、次の出力画面が生成されます-
フレームレイアウト
フレームレイアウトは、1つのアイテムのみを表示するために使用されます。 このレイアウトで複数のアイテムを互いにオーバーラップさせずに配置することは困難です。
新しいプロジェクトを開始し、 frameLayoutApp と呼びます。 以下に示すように、新しいフレームレイアウトを作成します。
<?xml version = "1.0" encoding = "utf-8"?>
<FrameLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<ImageView
android:id = "@+id/ImageView1"
android:scaleType = "matrix"
android:layout_height = "fill_parent"
android:layout_width = "fill_parent"
android:src = "@drawable/img1"/>
<TextView
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:textSize = "50dp"
android:textColor = "#000"
android:text = "This is a Lake"/>
<TextView
android:gravity = "right"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:textSize = "50dp"
android:text = "A very Deep Lake"
android:layout_gravity = "bottom"
android:textColor = "#fff"/>
</FrameLayout>
上記のコードは、画面全体を埋める imageView を作成します。 次に、2つのテキストビューが imageView の上に浮かびます。
次に、アプリケーションをビルドして実行します。 次の出力が表示されます-
テーブルレイアウト
このレイアウトでは、ビューは*行*および*列*に配置されます。 仕組みを見てみましょう。
<?xml version = "1.0" encoding = "utf-8"?>
<TableLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "fill_parent"
android:background = "#d3d3d3"
android:layout_height = "fill_parent"
android:stretchColumns = "1">
<TableRow>
<TextView
android:text = "First Name:"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textColor = "@android:color/black"/>
<EditText
android:width = "100px"
android:layout_width = "fill_parent"
android:layout_height = "30dp"
android:textColor = "@android:color/black"/>
</TableRow>
<TableRow>
<TextView
android:text = "Last Name:"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textColor = "@android:color/black"/>
<EditText
android:width = "50px"
android:layout_width = "fill_parent"
android:layout_height = "30dp"
android:textColor = "@android:color/black"/>
</TableRow>
<TableRow>
<TextView
android:text = "Residence:"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textColor = "@android:color/black"/>
<EditText
android:width = "100px"
android:layout_width = "fill_parent"
android:layout_height = "30dp"
android:textColor = "@android:color/black"/>
</TableRow>
<TableRow>
<TextView
android:text = "Occupation:"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textColor = "@android:color/black"/>
<EditText
android:width = "100px"
android:layout_width = "fill_parent"
android:layout_height = "30dp"
android:textColor = "@android:color/black"/>
</TableRow>
<TableRow>
<Button
android:text = "Cancel"
android:layout_width = "wrap_content"
android:layout_margin = "10dp"
android:layout_height = "wrap_content"
android:background = "@android:color/holo_green_dark"/>
<Button
android:text = "Submit"
android:width = "100px"
android:layout_margin = "10dp"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:background = "@android:color/holo_green_dark"/>
</TableRow>
</TableLayout>
上記のコードは、 tables および rows を使用して配置された単純なデータ入力フォームを作成します。
Xamarin-Androidウィジェット
日付ピッカー
これは、日付を表示するために使用されるウィジェットです。 この例では、テキストビューに設定された日付を表示する日付ピッカーを作成します。
まず、新しいプロジェクトを作成し、 datePickerExample と呼びます。 Main.axml を開き、 datepicker 、 textview 、および button を作成します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<DatePicker
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/datePicker1"/>
<TextView
android:text = "Current Date"
android:textAppearance = "?android:attr/textAppearanceLarge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/txtShowDate"/>
<Button
android:text = "Select Date"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/btnSetDate"/>
</LinearLayout>
次に、 Mainactivity.cs に移動します。 最初に、 mainActivity:Activity クラス内にtextviewのプライベートインスタンスを作成します。
インスタンスは、選択した日付またはデフォルトの日付を保存するために使用されます。
private TextView showCurrentDate;
次に、* setContentView()*メソッドの後に次のコードを追加します。
DatePicker pickDate = FindViewById<DatePicker>(Resource.Id.datePicker1);
showCurrentDate = FindViewById<TextView>(Resource.Id.txtShowDate);
setCurrentDate();
Button button = FindViewById<Button>(Resource.Id.btnSetDate);
button.Click += delegate {
showCurrentDate.Text = String.Format("{0}/{1}/{2}",
pickDate.Month, pickDate.DayOfMonth, pickDate.Year);
};
上記のコードでは、 FindViewById クラスを使用して main.axml ファイルからdatepicker、textview、およびbuttonを検索することで参照しています。
参照した後、選択した日付を日付ピッカーからテキストビューに渡すボタンクリックイベントを設定します。
次に、デフォルトの現在の日付をテキストビューに表示するための* setCurrentDate()*メソッドを作成します。 次のコードは、その方法を説明しています。
private void setCurrentDate() {
string TodaysDate = string.Format("{0}",
DateTime.Now.ToString("M/d/yyyy").PadLeft(2, '0'));
showCurrentDate.Text = TodaysDate;
}
- DateTime.Now.ToString()*クラスは、今日の時刻を文字列オブジェクトにバインドします。
次に、アプリをビルドして実行します。 それは次の出力を表示する必要があります-
タイムピッカー
タイムピッカーは、ユーザーが時間を選択および設定できるようにするだけでなく、時間を表示するために使用されるウィジェットです。 時刻を表示し、ユーザーが時刻を変更できる基本的なタイムピッカーアプリを作成します。
*main.axml* に移動し、次のコードに示すように、新しいボタン、テキストビュー、およびタイムピッカーを追加します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:background = "#d3d3d3"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<TimePicker
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/timePicker1"/>
<TextView
android:text = "Time"
android:textAppearance = "?android:attr/textAppearanceLarge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/txt_showTime"
android:textColor = "@android:color/black"/>
<Button
android:text = "Set Time"
android:layout_width = "200dp"
android:layout_height = "wrap_content"
android:id = "@+id/btnSetTime"
android:textColor = "@android:color/black"
android:background = "@android:color/holo_green_dark"/>
</LinearLayout>
*MainActivity.cs* に移動して、作成したテキストビューに設定された日付を表示する機能を追加します。
public class MainActivity : Activity {
private TextView showCurrentTime;
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
TimePicker Tpicker = FindViewById<TimePicker>(Resource.Id.timePicker1);
showCurrentTime = FindViewById<TextView>(Resource.Id.txt_showTime);
setCurrentTime();
Button button = FindViewById<Button>(Resource.Id.btnSetTime);
button.Click += delegate {
showCurrentTime.Text = String.Format("{0}:{1}",
Tpicker.CurrentHour, Tpicker.CurrentMinute);
};
}
private void setCurrentTime() {
string time = string.Format("{0}",
DateTime.Now.ToString("HH:mm").PadLeft(2, '0'));
showCurrentTime.Text = time;
}
}
上記のコードでは、最初に timepicker 、 set time ボタンと FindViewById <> クラスで時間を表示するためのテキストビューを参照しました。 次に、時間を設定するボタンのクリックイベントを作成し、クリックすると時間を人が選択した時間に設定します。 デフォルトでは、現在のシステム時刻が表示されます。
- setCurrentTime()メソッドクラスは、 *txt_showTime テキストビューを初期化して現在の時刻を表示します。
次に、アプリケーションをビルドして実行します。 それは次の出力を表示する必要があります-
スピナー
スピナーは、セットから1つのオプションを選択するために使用されるウィジェットです。 これは、ドロップダウン/コンボボックスに相当します。 まず、新しいプロジェクトを作成し、 Spinner App Tutorial と呼びます。
- layoutフォルダーの下の Main.axml を開き、新しい spinner を作成します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<Spinner
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/spinner1"
android:prompt = "@string/daysOfWeek"/>
</LinearLayout>
- valuesフォルダ*にある Strings.xml ファイルを開き、次のコードを追加して*スピナーアイテム*を作成します。
<resources>
<string name = "daysOfWeek">Choose a planet</string>
<string-array name = "days_array">
<item>Sunday</item>
<item>Monday</item>
<item>Tuesday</item>
<item>Wednesday</item>
<item>Thursday</item>
<item>Friday</item>
<item>Saturday</item>
<item>Sunday</item>
</string-array>
</resources>
次に、 MainActivity.cs を開いて、選択した曜日を表示する機能を追加します。
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
//Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
Spinner spinnerDays = FindViewById<Spinner>(Resource.Id.spinner1);
spinnerDays.ItemSelected += new EventHandler
<AdapterView.ItemSelectedEventArgs>(SelectedDay);
var adapter = ArrayAdapter.CreateFromResource(this,
Resource.Array.days_array, Android.Resource.Layout.SimpleSpinnerItem);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropD ownItem);
spinnerDays.Adapter = adapter;
}
private void SelectedDay(object sender, AdapterView.ItemSelectedEventArgs e) {
Spinner spinner = (Spinner)sender;
string toast = string.Format("The selected
day is {0}", spinner.GetItemAtPosition(e.Position));
Toast.MakeText(this, toast, ToastLength.Long).Show();
}
次に、アプリケーションをビルドして実行します。 それは次の出力を表示する必要があります-
上記のコードでは、 main.axml ファイルで作成したスピナーを FindViewById <> クラスを介して参照しました。 次に、 strings.xml クラスの配列項目をバインドするために使用する新しい* arrayAdapter()*を作成しました。
最後に、選択した曜日を表示するために使用するメソッド* SelectedDay()*を作成しました。
Xamarin-Androidダイアログ
警告ダイアログ
このセクションでは、クリックするとアラートダイアログボックスを表示するボタンを作成します。 ダイアログボックスには、2つのボタン、 Delete および Cancel ボタンが含まれています。
まず、 main.axml に移動し、次のコードに示すように、線形レイアウト内に新しいボタンを作成します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:background = "#d3d3d3"
android:layout_height = "fill_parent">
<Button
android:id="@+id/MyButton"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "Click to Delete"
android:textColor = "@android:color/background_dark"
android:background = "@android:color/holo_green_dark"/>
</LinearLayout>
次に、 MainActivity.cs を開いてアラートダイアログを作成し、その機能を追加します。
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate {
AlertDialog.Builder alertDiag = new AlertDialog.Builder(this);
alertDiag.SetTitle("Confirm delete");
alertDiag.SetMessage("Once deleted the move cannot be undone");
alertDiag.SetPositiveButton("Delete", (senderAlert, args) => {
Toast.MakeText(this, "Deleted", ToastLength.Short).Show();
});
alertDiag.SetNegativeButton("Cancel", (senderAlert, args) => {
alertDiag.Dispose();
});
Dialog diag = alertDiag.Create();
diag.Show();
};
}
完了したら、アプリケーションをビルドして実行し、結果を表示します。
上記のコードでは、alertDiagというアラートダイアログを作成し、次の2つのボタンを備えています-
- setPositiveButton -クリックすると確認メッセージ Deleted を表示する Delete ボタンアクションが含まれます。
- setNegativeButton -クリックすると、アラートダイアログボックスを単純に閉じる*キャンセル*ボタンが含まれます。
Xamarin-ギャラリー
ギャラリーは、水平スクロール可能なリストにアイテムを表示するために使用されるビューの一種です。 選択したアイテムが中央に表示されます。 この例では、水平方向にスクロール可能な画像を含むギャラリーを作成します。 画像をクリックすると、選択した画像の番号が表示されます。
まず、新しいプロジェクトを作成し、名前を付けます(Gallery App Tutorialなど)。 コーディングを開始する前に、7つの画像を* resource/drawableフォルダー*に貼り付けます。 resources folder の下の main.axml と、線形レイアウトタグの間にあるギャラリーに移動します。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#d3d3d3">
<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"/>
</LinearLayout>
*_ImageAdapter_* という新しいクラスを作成します。 このクラスは、上で作成したギャラリーに画像をバインドするために使用されます。
最初のステップは、フィールドを保存するために使用するコンテキスト cont を含むクラスを追加することです。
public class ImageAdapter : BaseAdapter {
Context cont;
public ImageAdapter(Context ct) {
cont = ct;
}
}
次に、画像を含みそのサイズを返す配列リストをカウントします。
public override int Count {
get {
return imageArraylist.Length;
}
}
次のステップでは、アイテムの位置を取得します。 次のコードは、その方法を示しています。
public override Java.Lang.Object GetItem(int position) {
return null;
}
public override long GetItemId(int position) {
return 0;
}
次のステップでは、アダプターによって参照されるアイテムの imageview を作成します。
public override View GetView(int position,View convertView, ViewGroup parent) {
ImageView img = new ImageView(cont);
img.SetImageResource(imageArraylist[position]);
img.SetScaleType(ImageView.ScaleType.FitXy);
img.LayoutParameters = new Gallery.LayoutParams(200, 100);
return img;
}
最後のステップでは、 resources.drawable フォルダーに追加した画像への参照を作成します。 これを行うには、画像のコレクションを保持する配列を作成します。 次のコードは、その方法を説明しています。
int[] imageArraylist = {
Resource.Drawable.img1,
Resource.Drawable.img2,
Resource.Drawable.img3,
Resource.Drawable.img4,
Resource.Drawable.img5,
Resource.Drawable.img6,
};
}
次に、 mainActivity.cs に移動して、OnCreate()メソッドの下に次のコードを挿入します。
Gallery myGallery = (Gallery)FindViewById<Gallery>(Resource.Id.gallery);
myGallery.Adapter = new ImageAdapter(this);
myGallery.ItemClick += delegate(object sender, AdapterView.ItemClickEventArgs args) {
Toast.MakeText(this,
args.Position.ToString(), ToastLength.Short).Show();
}
最後に、アプリケーションをビルドして実行し、出力を表示します。
Xamarin-Andriodビュー
リストビュー
リストビューは、スクロール可能なアイテムのリストを表示するユーザーインターフェイス要素です。
リストビューへのデータのバインド
この例では、曜日を表示するlistViewを作成します。 まず、新しいXMLファイルを作成して、 listViewTemplate.xml という名前を付けます。
*listViewTemplate.xml* で、次のように新しいテキストビューを追加します。
<?xml version = "1.0" encoding = "utf-8" ?>
<TextView xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/textItem"
android:textSize ="20sp"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"/>
次に、 Main.axml に移動して、線形レイアウト内に新しいリストビューを作成します。
<ListView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView1"/>
*MainActivity.cs* を開き、次のコードを入力して、作成したリストビューにデータをバインドします。 コードは* OnCreate()*メソッド内に記述する必要があります。
SetContentView(Resource.Layout.Main);
var listView = FindViewById<ListView>(Resource.Id.listView1);
var data = new string[] {
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
};
listView.Adapter = new ArrayAdapter(this, Resource.Layout.ListViewTemplate, data);
*Var data = new string []* は、単にアイテムを配列として保持します。
配列アダプタは、コレクション内のアイテムをビューとして返します。 デフォルトでは、Array AdapterはデフォルトのtextViewを使用して各アイテムを表示します。 上記のコードでは、 ListViewTemplate.xml に独自のテキストビューを作成し、以下に示すコンストラクターを使用してそれを参照しました。
ArrayAdapter(this, Resource.Layout.ListViewTemplate, data);
最後に、アプリケーションをビルドして実行し、出力を表示します。
GridViews
gridViewは、アプリケーションがコンテンツを2次元の方法でスクロール可能なグリッドにレイアウトできるようにするビューグループです。
GridViewを追加するには、新しいプロジェクトを作成し、 gridViewApp と呼びます。 Main.axml に移動し、以下に示すようにグリッドを追加します。
<?xml version = "1.0" encoding="utf-8"?>
<GridView xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/gridview"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:columnWidth = "90dp"
android:numColumns = "auto_fit"
android:verticalSpacing = "10dp"
android:horizontalSpacing = "10dp"
android:stretchMode = "columnWidth"
android:gravity = "center"/>
次に、新しいクラスを作成し、 ImageAdpter.cs という名前を付けます。 このクラスには、グリッドに表示されるすべてのアイテムのアダプタークラスが含まれます。
*ImageAdapter* 内に、次のコードを追加します-
public class ImageAdapter : BaseAdapter {
Context context;
public ImageAdapter(Context ch) {
context = ch;
}
public override int Count {
get {
return cars.Length;
}
}
public override long GetItemId(int position) {
return 0;
}
public override Java.Lang.Object GetItem(int position) {
return null;
}
public override View GetView(int position,
View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.LayoutParameters = new GridView.LayoutParams(100, 100);
imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
imageView.SetPadding(8, 8, 8, 8);
} else {
imageView = (ImageView)convertView;
}
imageView.SetImageResource(cars[position]);
return imageView;
}
int[] cars = {
Resource.Drawable.img1, Resource.Drawable.img2,
Resource.Drawable.img3, Resource.Drawable.img4,
Resource.Drawable.img5, Resource.Drawable.img6,
};
}
上記のコードでは、単に車の画像を画像アダプターにバインドしています。 次に、 MainActivity.cs を開き、* setContentView()*の後に次のコードを追加します。
var gridview = FindViewById<GridView>(Resource.Id.gridview);
gridview.Adapter = new ImageAdapter(this);
gridview.ItemClick += delegate(object sender,
AdapterView.ItemClickEventArgs args) {
Toast.MakeText(this,
args.Position.ToString(), ToastLength.Short).Show();
};
上記のコードは、 main.axml でgridViewを見つけ、 imageAdapter クラスにバインドします。 Gridview.ItemClick は、ユーザーが画像をクリックしたときに選択した画像の位置を返す onClick イベントを作成します。
次に、アプリケーションをビルドして実行し、出力を表示します。
Xamarin-マルチスクリーンアプリ
この章では、ユーザーが登録できるようにするログインシステムを作成します。 次に、ログインに成功すると、登録ユーザーをアプリのホーム画面に移動します。
まず、新しいプロジェクトを作成し、 Login System と呼びます。 新しいプロジェクトで、 main.axml に移動し、以下に示すように2つのボタンと進行状況バーを追加します。
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:background = "@android:color/background_light"
android:weightSum = "100"
android:minWidth = "25px"
android:minHeight = "25px">
<TextView
android:text = "Login App"
android:textAppearance = "?android:attr/textAppearanceMedium"
android:layout_width = "match_parent"
android:layout_weight = "20"
android:layout_height = "0dp"
android:textColor = "#368DEB"
android:id = "@+id/txtCreatAccount"
android:gravity = "center"
android:textStyle = "bold"
android:textSize = "25sp"/>
<Button
android:text = "Sign In"
android:layout_width = "match_parent"
android:layout_weight = "15"
android:layout_height = "0dp"
android:background = "@drawable/btnSignInStyle"
android:id = "@+id/btnSignIn"
android:layout_marginLeft = "20dp"
android:layout_marginRight = "20dp"
android:textSize = "15sp"/>
<Button
android:text = "Sign Up"
android:layout_width = "match_parent"
android:layout_weight = "15"
android:layout_height = "0dp"
android:background = "@drawable/btnSignUpStyle"
android:id = "@+id/btnSignUp"
android:layout_marginLeft = "20dp"
android:layout_marginRight = "20dp"
android:textSize = "15sp"/>
<RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "0dp"
android:layout_weight = "50"
android:minWidth = "25px"
android:minHeight = "25px">
<ProgressBar
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/progressBar1"
android:background = "@drawable/progressBarStyle"
android:layout_centerInParent="true"
android:indeterminate = "true"
xmlns:tools = "
http://schemas.android.com/tools"
tools:visibility = "invisible"/>
</RelativeLayout>
</LinearLayout>
ユーザーインターフェースを作成したら、ボタンをより魅力的に見せるようにスタイルを設定することが重要です。 これを行うには、 drawable folder の下に新しいXMLファイルを作成し、ファイルに btnSignInStyle.xml という名前を付けます。
XMLファイルでは、次のコード行を追加します-
<selector xmlns:android = "http://schemas.android.com/apk/res/android">
<item android:state_pressed = "false">
<layer-list>
<item android:right = "5dp" android:top = "5dp">
<shape>
<corners android:radius = "2dp"/>
<solid android:color = "#D6D6D6"/>
</shape>
</item>
<item android:left = "2dp" android:bottom = "2dp">
<shape>
<corners android:radius = "4dp"/>
<gradient android:angle = "270"
android:endColor = "#486EA9" android:startColor = "#486EA9"/>
<stroke android:width = "1dp" android:color = "#BABABA"/>
<padding android:bottom = "10dp"
android:right = "10dp" android:left = "10dp" android:top = "10dp"/>
</shape>
</item>
</layer-list>
</item>
<item android:state_pressed = "true">
<layer-list>
<item android:right = "5dp" android:top = "5dp">
<shape>
<corners android:radius = "2dp"/>
<solid android:color = "#D6D6D6"/>
</shape>
</item>
<item android:left = "2dp" android:bottom = "2dp">
<shape>
<corners android:radius = "4dp"/>
<gradient android:angle = "270"
android:endColor = "#79C791" android:startColor = "#486EA9"/>
<stroke android:radius = "4dp" android:color = "#BABABA"/>
<padding android:bottom = "10dp"
android:right = "10dp" android:left = "10dp" android:top = "10dp"/>
</shape>
</item>
</layer-list>
</item>
</selector>
上記のコードは、ロード時およびクリック時にボタンの色を設定し、ボタンの境界線の半径も設定します。
次に、 signup ボタンに対して上記と同様のスタイリングXMLを作成します。 これを行うには、 drawable フォルダーの下に別のXMLを作成し、 btnSignUpStyle.xml を呼び出します。 btnSignInStyle.xml からすべてを継承します。 唯一の違いは、ボタンのグラデーションの開始色と終了色です。
*btnSignUpStyle.xml* の *startColor* および *endColor* を変更します
<gradient android:angle="270"
android:endColor="#008000" android:startColor="#008000"/>
*layout folder* に移動して、新しいAXMLファイルを作成し、registerDailog.axmlと呼びます。 このファイルには、アプリの新規ユーザーの登録詳細が含まれます。 このページには、3つの *EditTexts* とデータを送信するボタンが含まれます。 線形レイアウトコード内に次のコードを追加します。
<EditText
android:layout_width = "match_parent"
android:layout_marginBottom = "10dp"
android:layout_marginTop = "25dp"
android:layout_marginRight = "25dp"
android:layout_marginLeft = "25dp"
android:layout_height = "35dp"
android:paddingLeft = "10dp"
android:id = "@+id/txtUsername"
android:hint = "Username"
android:textColor = "#000"/>
<EditText
android:layout_width = "match_parent"
android:layout_height = "35dp"
android:id = "@+id/txtEmail"
android:layout_marginBottom = "10dp"
android:layout_marginTop = "25dp"
android:layout_marginRight = "25dp"
android:layout_marginLeft = "25dp"
android:paddingLeft = "10dp"
android:textColor = "#000"
android:hint = "Email"/>
<EditText
android:layout_width = "match_parent"
android:layout_height = "35dp"
android:layout_marginBottom = "10dp"
android:layout_marginTop = "25dp"
android:layout_marginRight = "25dp"
android:layout_marginLeft = "25dp"
android:paddingLeft = "10dp"
android:textColor = "#000"
android:id = "@+id/txtPassword"
android:hint = "Password"/>
<Button
android:text = "Sign Up"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/btnSave"
android:textSize = "20dp"
android:textColor = "#fff"
android:textStyle = "bold"
android:height = "70dp"
android:background = "@drawable/btnSignUpStyle"
android:paddingLeft = "5dp"
android:paddingRight = "5dp"
android:paddingTop = "5dp"
android:paddingBottom = "5dp"
android:layout_marginLeft = "25dp"
android:layout_marginRight = "25dp"
android:layout_centerHorizontal = "true"/>
次に、 signUpDialog.cs という新しいクラスを追加します。 このクラスには、ダイアログボックスの作成に必要なコードが含まれます。 次の例はコードを示しています。
public class OnSignUpEvent:EventArgs {
private string myUserName;
private string myEmail;
private string myPassword;
public string UserName {
get {
return myUserName;
}
set{
myUserName = value;
}
}
public string Email {
get {
return myEmail;
}
set {
myEmail = value;
}
}
public string Password {
get {
return myPassword;
}
set {
myPassword = value;
}
}
public OnSignUpEvent(string username, string
email, string password):base() {
UserName = username;
Email = email;
Password = password;
}
class SignUpDialog:DialogFragment {
private EditText txtUsername;
private EditText txtEmail;
private EditText txtPassword;
private Button btnSaveSignUp;
public event EventHandler<OnSignUpEvent> onSignUpComplete;
public override View OnCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
base.OnCreateView(inflater, container, savedInstanceState);
var view = inflater.Inflate(Resource.Layout.registerDialog, container, false);
txtUsername = view.FindViewById<EditText>(Resource.Id.txtUsername);
txtEmail = view.FindViewById<EditText>(Resource.Id.txtEmail);
txtPassword = view.FindViewById<EditText>(Resource.Id.txtPassword);
btnSaveSignUp = view.FindViewById<Button>(Resource.Id.btnSave);
btnSaveSignUp.Click += btnSaveSignUp_Click;
return view;
}
void btnSaveSignUp_Click(object sender, EventArgs e) {
onSignUpComplete.Invoke(this, new OnSignUpEvent(txtUsername.Text,
txtEmail.Text, txtPassword.Text));
this.Dismiss();
}
}
}
上記のコードでは、 get および set プロパティを使用しました。 get メソッドは変数を返し、 set メソッドは返された変数に値を割り当てます。 ここに例があります-
public string Color {
get {
return color;
}
set {
color = value;
}
}
前の例では、ビューをオーバーライドするメソッドを作成しました。 メソッド内で、レイアウトフォルダに含まれる registerDialog.axml を参照する view という var を作成しました。
次に、 mainActivity.cs に移動して、ダイアログフラグメントを作成します。
private Button signUp;
private Button submitNewUser;
private EditText txtUsername;
private EditText txtEmail;
private EditText txtPassword;
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
signUp = FindViewById<Button>(Resource.Id.btnSignUp);
submitNewUser = FindViewById<Button>(Resource.Id.btnSave);
txtUsername = FindViewById<EditText>(Resource.Id.txtUsername);
txtEmail = FindViewById<EditText>(Resource.Id.txtEmail);
txtPassword = FindViewById<EditText>(Resource.Id.txtPassword);
signUp.Click += (object sender, EventArgs args) => {
FragmentTransaction transFrag = FragmentManager.BeginTransaction();
SignUpDialog diagSignUp = new SignUpDialog();
diagSignUp.Show(transFrag, "Fragment Dialog");
diagSignUp.onSignUpComplete += diagSignUp_onSignUpComplete;
};
}
void diagSignUp_onSignUpComplete(object sender, OnSignUpEvent e) {
StartActivity(typeof(Activity2));
}
上記のコードには、クリックするとsignUpダイアログをロードするボタンクリックイベントが含まれています。 ボタンクリック内で、 registerDialog.axml ファイルをロードする SignUpDialog クラスを作成しました。
次に、 FragmentTransaction transFrag = FragmentManager.BeginTransaction(); を使用して、 registerDialog ページをAndroid Dialog Fragmentとして表示しました。
*home.axml* という別の *.axml* ファイルを追加します。 ユーザーがシステムに正常にログインすると、このレイアウトがランディング画面になります。 このレイアウト内に、次のコードに示すようにテキストビューを追加します。
<TextView
android:text = "You have been succesfully registered. Welcome!"
android:textAppearance = "?android:attr/textAppearanceLarge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/textView1"/>
次に、 Activity2.cs という最終アクティビティを作成します。 このアクティビティでは、 findViewById を使用して home.axml を検索します。
最後に、アプリをビルドして実行します。 出力として次の画面が表示されます。
Xamarin-アプリの展開
アプリの構築プロセスを完了した後、物理的なAndroidデバイスでこのアプリを使用するか、他のユーザーがアプリをダウンロードしてデバイスにインストールできるようにすることが重要です。
アプリをリリースする
アプリをリリースする前に、Androidシステムで読み取れる形式に変換することが重要です。 このタイプの形式は、* apkファイル*と呼ばれます。 * apkファイル*を作成します。
- プロジェクトを開きます。
- [ビルド]メニューに移動し、[構成マネージャー]を選択します*
- Configuration Managerで、 Active Solution Configuration を設定してアプリをリリースします。
次に、[ビルドメニュー]をもう一度クリックし、[Androidパッケージ(.apk)のエクスポート]を選択します。
終了すると、 apk ファイルはプロジェクトフォルダー /bin/Release に保存されます。
アプリを公開する
アプリを公開する3つの方法があります-
オンライン添付
*apk* ファイルを添付ファイルとしてオンラインでアップロードする必要があります。 その後、Androidデバイスを持っているユーザーは、自分のデバイスにアプリをダウンロードして直接インストールできます。
グーグルプレイストア
PlayStoreはAndroidアプリの最大の市場です。 アプリをPlayStoreにアップロードするには、Googleの開発者アカウントが必要です。 開発者アカウントは一度作成され、ライセンスを取得するのに25ドルかかります。
手動インストール
手動インストールには、物理デバイスに直接生成された .apk ファイルのインストールが含まれます。 ファイルをAndroidデバイスの物理メモリまたはSDカードにコピーしてから、デバイスからファイルを実行します。
Androidはデフォルトで、PlayStore以外からのアプリのインストールをブロックします。 アプリをインストールするには、*設定*からアプリのインストールを受け入れるようにアプリを有効にする必要があります。 これを行うには、デバイスの[設定]に移動し、[セキュリティ]メニューを探して、[不明なソースからのアプリのインストールを許可する]をオンにします。