如何在android中动态添加UI元素

时间:2016-06-16 18:34:51

标签: android visual-studio xamarin

我一直在寻找如何纯粹通过代码创建UI元素

我该怎么做?

RelativeLayout mainLayout = FindViewById<RelativeLayout>(Resource.Id.MainRelativeLayout);
TextView newText = new TextView(this);
newText.Text = "HEY THERE NEW TEXT MADE VIA CODE";
mainLayout.AddView(newText);


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

1 个答案:

答案 0 :(得分:0)

事实证明,您需要在设置内容视图后放置代码

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

RelativeLayout mainLayout = FindViewById<RelativeLayout>(Resource.Id.MainRelativeLayout);
TextView newText = new TextView(this);
newText.Text = "HEY THERE NEW TEXT MADE VIA CODE";
mainLayout.AddView(newText);

哦,你需要在FindViewById&lt;下指定类型TYPE&gt;