Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to programmatically add button to view

In my Android activity, I create a custom view that extends SurfaceView (using MonoDroid so slight variations in syntax):

class FriendsView : SurfaceView
{
    ...

    public FriendsView(Context context) : base(context)
    {

        ... create my custom view ...

    }


}

In my Activity class, I set the content view to the view:

protected override void OnCreate(Bundle bundle)
{

    base.OnCreate(bundle);

    ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.FillParent);

    FriendsView friendsView = new FriendsView(this);

    SetContentView(friendsView, layoutParams);

}

I want to add a button to the view, but cannot work out how to do this. Everything I have read starts from the point of view of the main.xml, but I don't see how to use this to declare a button which is visible in my view. Equally, I cannot find a method in either Activity or View classes which lets me add a Button object programatically.

I feel sure I am missing something conceptually, but would welcome any help to get me going in the right direction.

like image 797
user304582 Avatar asked Jan 23 '11 19:01

user304582


2 Answers

If I understand correctly you see your friendsView just fine, but you want to add a button to it? I don't know what kind of View your FriendsView is, but assuming it is something you can add childs to (like a linearLayout or something), you should be able to do this (just from the top of my head)

 //assuming you have a friendsView object that is some sort of Layout.
 Button yourButton = new ImageButton(this);
 //do stuff like add text and listeners.

 friendsView.addView(yourButton);

If there is some other element in friendsView you want to add a child to, you can just find it using findViewById() (add ids to your elements if you want to find them like this)

like image 68
Nanne Avatar answered Nov 06 '22 18:11

Nanne


A SurfaceView can not have childs, only the Views based on a ViewGroup can (LinearLayout, RelativeLayout,...) I guess you want to use a LinearLayout for your ContentView(), or rather a RelativeLayout (if the Button should be "inside" the SurfaceView). For LinearLayout, you have to take care of the layout orientation (setOrientation()), for RelativeLayout you have to take very special care about the LayoutParams of the childs which will define the relative coordinates/positions of the childs inside the RelativeLayout.

Best would be if you inflate all from XML. You can also inflate your "own" Views by using the full classname in the XML file. There basically is no need to put together a ContentView by yourself.

like image 5
Oliver Avatar answered Nov 06 '22 18:11

Oliver