编程/动态添加按钮控件使用单声道为Android {例如}查看 [英] Programmatically/Dynamically Add Button Controls to View using Mono for Android {example}

查看:158
本文介绍了编程/动态添加按钮控件使用单声道为Android {例如}查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找如何动态地从活动添加控件的一个例子。

Looking for an example of how to dynamically add controls from the activity.

内的活动,让我们把它称为Activity2.cs,动态添加按钮的变量数MyView.axml。

Inside an activity, lets call it "Activity2.cs", dynamically add a variable number of buttons to "MyView.axml".

我在寻找code像下面(除code,实际工作):

I'm looking for code like below (except code that actually works):

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

的结果将是四个按钮被添加在视图的底部。我可以用单声道为Android(即在Visual Studio),当发现示例如何动态地在Android中添加控件,但不是。

The result would be that four buttons are added at the bottom of the view. I can find examples for how to dynamically add controls in Android, but not when using Mono for Android (ie in Visual Studio).

推荐答案

假设您的布局文件看起来像这样(Main.axml):

Let's say your layout file looks like this (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>

然后在你的活动,你可以添加按钮对象,这样的布局:

Then in your activity you can add Button objects to the layout like this:

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

这篇关于编程/动态添加按钮控件使用单声道为Android {例如}查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆