开发者

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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜