使用 Mono for Android {example} 以编程方式/动态方式将按钮控件添加到视图 [英] Programmatically/Dynamically Add Button Controls to View using Mono for Android {example}

查看:17
本文介绍了使用 Mono for Android {example} 以编程方式/动态方式将按钮控件添加到视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在寻找如何从 Activity 动态添加控件的示例.

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".

我正在寻找如下代码(实际工作的代码除外):

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 中动态添加控件的示例,但在使用 Mono for Android(即在 Visual Studio 中)时则无法找到.

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>

然后在您的活动中,您可以将 Button 对象添加到布局中,如下所示:

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

这篇关于使用 Mono for Android {example} 以编程方式/动态方式将按钮控件添加到视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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