miko
miko

Reputation: 89

How to automatically add layout elements with c#?

I want to add elements into my layout automatically, how do I do that? For example a textview appears when a user clicks a button

Upvotes: 2

Views: 145

Answers (3)

Alessandro Caliaro
Alessandro Caliaro

Reputation: 5768

I don't know Xamarin.Android very well but I think the right way is to add controls to layout with "IsVisible = false", then set IsVisible = true.

Otherwise you can take a look to

LinearLayout principalview = FindViewById(Resource.Id.mainlayout);

    LinearLayout.LayoutParams parametros = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent);
    var valueB = new Button(this);
    valueB.Text = "Teste";
    valueB.SetBackgroundColor(Color.Aqua);
    principalview.AddView(valueB, parametros);

OR

var layout = new LinearLayout (this);
layout.Orientation = Orientation.Vertical;

var aLabel = new TextView (this);
aLabel.Text = "Hello, World!!!";

var aButton = new Button (this);
aButton.Text = "Say Hello!";

aButton.Click +=(sender, e) => 
{aLabel.Text="Hello Android!";};

layout.AddView (aLabel);
layout.AddView (aButton);
SetContentView (layout); 

Upvotes: 0

jzeferino
jzeferino

Reputation: 7850

To add a TextView or any other view in Android you must add the view you want to a view that support addition, one example is the LinearLayout.

If you have this layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lnrRootView"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

And then in you Activity add a TextView programaticlly to your LinearLayout.

public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

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

            var linearLayout = FindViewById<LinearLayout>(Resource.Id.lnrRootView);

            var textView = new TextView(this);
            textView.Text = "Added programaticlly";
            linearLayout.AddView(textView);
        }
    }

You will get something like this:

enter image description here

Upvotes: 1

Mike
Mike

Reputation: 24

Much depends on what you're trying to accomplish. You could simulate adding to layout by turning visibility of elements after certain event, eg. button click.

If you want to add elements dynamically during runtime, consider using ObservableCollection<T>

Link: https://developer.xamarin.com/api/type/System.Collections.ObjectModel.ObservableCollection%601/

Upvotes: 0

Related Questions