Android:如何以编程方式添加要查看的按钮 [英] Android: How to programmatically add button to view
问题描述
在我的 Android 活动中,我创建了一个扩展 SurfaceView 的自定义视图(使用 MonoDroid 在语法上有细微的变化):
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 ...
}
}
在我的 Activity 类中,我将内容视图设置为视图:
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);
}
我想在视图中添加一个按钮,但不知道如何执行此操作.我读过的所有内容都是从 main.xml 的角度开始的,但我不知道如何使用它来声明在我的视图中可见的按钮.同样,我在 Activity 或 View 类中都找不到允许我以编程方式添加 Button 对象的方法.
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.
推荐答案
如果我没理解错,你看到你的朋友视图就好了,但是你想给它添加一个按钮?我不知道你的 FriendsView 是什么样的 View,但假设它是你可以添加孩子的东西(比如 linearLayout 或其他东西),你应该能够做到这一点(只是从我的头顶)
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);
如果你想在friendsView中添加一些其他元素,你可以使用findViewById()
找到它(如果你想像这样找到它们,则将id添加到你的元素中)
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)
这篇关于Android:如何以编程方式添加要查看的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!