2012-01-29 3 views
1

アクティビティのコントロールを動的に追加する方法の例をお探しください。Android用のMonoを使用して表示するボタンコントロールをプログラムで/動的に追加する(例)

アクティビティの内部では、「Activity2.cs」という名前で、「MyView.axml」に可変数のボタンを動的に追加できます。私は(実際に動作するコードを除く)、以下のようなコードを探しています

 string[] textArray = new string[] { "button1", "button2", "button3", "button4" }; 
     int counter= 3; 

     for (int i = 0; i < length; i++) 
     { 

      var mytest = new button(this); 

      mytest.Text = textArray[i]; 
      mytest.id= textArray[i]; 

      View(MyView.axml).add(mytest); 
     } 

結果は、4つのボタンがビューの一番下に追加されていることだろう。私はAndroidでコントロールを動的に追加する方法の例を見つけることができますが、Android用にMonoを使用する場合(Visual Studioなど)はそうではありません。

答えて

3

のは、(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:id="@+id/Buttons"> 
</LinearLayout> 

次に、あなたの活動に、あなたがこのようなレイアウトにボタンオブジェクトを追加することができます。

[Activity(Label = "Buttons", MainLauncher = true, Icon = "@drawable/icon")] 
public class ButtonActivity : Activity 
{ 
    protected override void OnCreate(Bundle bundle) 
    { 
     base.OnCreate(bundle); 

     SetContentView(Resource.Layout.Main); 

     var buttons = FindViewById<LinearLayout>(Resource.Id.Buttons); 

     for (int i = 1; i <= 4; i++) 
     { 
      var button = new Button(this); 
      button.Text = "Button " + i; 
      button.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 
                   ViewGroup.LayoutParams.WrapContent); 

      buttons.AddView(button); 
     } 
    } 
} 
+0

私がまさに必要!迅速な答えをありがとう:) – Ariesto

関連する問題