Xamarin Android:如何将XML和C#结合起来

本文关键字:结合 起来 XML Android Xamarin | 更新日期: 2023-09-27 18:25:39

我是编程新手,我正在Mac上使用Xamarin Studio创建Android应用程序。

现在,我知道如何在代码中创建按钮、文本视图等,但我很难为它们设置样式。大多数在线解决方案都使用XML创建视图并对其进行样式设置,然后添加如下XML文件:

[Activity(Label = "ButtonStyle", MainLauncher = true, Icon = "@drawable/icon")]
public class Activity1 : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);
    }
}

你只能在SetContentView中添加一个"thing"(我没有更好的词来形容它),所以我不能决定做这样的事情:

SetContentView(Resource.Layout.Main);
SetContentView(MyView);

有没有一种方法可以同时使用XML和C#代码添加视图?

Xamarin Android:如何将XML和C#结合起来

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainLinearLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
    android:id="@+id/myButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />
</LinearLayout>

您可以通过这样的代码将内容动态添加到现有布局中。

Button btn = new Button (this);
btn.Text = "Added Button";
LinearLayout mainLinearLayout = (LinearLayout)FindViewById (Resource.Id.mainLinearLayout);
mainLinearLayout.AddView (btn);

现在您应该在页面中看到两个按钮。