简体   繁体   中英

Xamarin Android: How to combine XML and C#?

I am new to programming and I'm using Xamarin Studio on my Mac to create Android applications.

Now, I know how to create buttons, TextViews, etc. in code, but I am having a hard time styling them. Most solutions online use XML to create the views and style them, and then add the XML file like this:

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

You can only add one 'thing' (I don't have a better word for it) to the SetContentView, so I can't decide to do something like:

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

Is there a way for me to add views with both XML and C# code?

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

You can dynamically add contents to existing Layout from code like this.

Button btn = new Button (this);
btn.Text = "Added Button";

LinearLayout mainLinearLayout = (LinearLayout)FindViewById (Resource.Id.mainLinearLayout);
mainLinearLayout.AddView (btn);

Now you should see two buttons in the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM