Skip to content Skip to sidebar Skip to footer

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 Frie

Solution 1:

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.ButtonyourButton=newImageButton(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)

Solution 2:

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.

Post a Comment for "Android: How To Programmatically Add Button To View"