Android:如何以编程方式添加按钮进行查看

use*_*582 7 android view add button

在我的Android活动中,我创建了一个扩展SurfaceView的自定义视图(使用MonoDroid,语法略有不同):

class FriendsView : SurfaceView
{
    ...

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

        ... create my custom view ...

    }


}
Run Code Online (Sandbox Code Playgroud)

在我的Activity类中,我将内容视图设置为视图:

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

}
Run Code Online (Sandbox Code Playgroud)

我想在视图中添加一个按钮,但无法解决如何执行此操作.我读过的所有内容都是从main.xml的角度出发的,但是我没有看到如何使用它来声明一个在我的视图中可见的按钮.同样,我无法在Activity或View类中找到一个方法,它允许我以编程方式添加Button对象.

我确信我在概念上遗漏了一些东西,但欢迎任何帮助让我朝着正确的方向前进.

Nan*_*nne 13

如果我理解正确你看到你的朋友看得很好,但你想添加一个按钮吗?我不知道你的FriendsView是什么样的,但是假设它是你可以添加孩子的东西(比如linearLayout或其他东西),你应该能够做到这一点(就在我的脑海中)

 //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);
Run Code Online (Sandbox Code Playgroud)

如果在friendsView中有一些其他元素你想要添加一个子元素,你可以使用它来找到它findViewById()(如果你想像这样找到它们,可以在你的元素中添加id)


Oli*_*ver 5

SurfaceView不能有子级,只有基于ViewGroup的视图才可以(LinearLayout,RelativeLayout等)。我猜您想为您的ContentView()使用LinearLayout,或者是为RelativeLayout(如果Button应该位于“内部” “ SurfaceView)。对于LinearLayout,您必须注意布局方向(setOrientation()),对于RelativeLayout,您必须特别注意子项的LayoutParam,这些子项将在RelativeLayout中定义子项的相对坐标/位置。

最好的办法是将XML全部充实。您还可以通过使用XML文件中的完整类名来扩展“自己的”视图。基本上没有必要自己整理ContentView。