Java 是否可以将按钮添加到以编程方式设置的框架布局中?

Java 是否可以将按钮添加到以编程方式设置的框架布局中?,java,android,android-linearlayout,android-framelayout,Java,Android,Android Linearlayout,Android Framelayout,这有点难以描述,但我会尽全力: 我正在开发一个android应用程序,使用自定义的摄像头活动。在本相机活动中,我使用编程方式创建曲面视图,并将其设置为xml布局文件中定义的framelayout(覆盖全屏) 我现在的问题是,如何向框架布局添加其他元素?仅以编程方式?我这样问是因为到目前为止,我只能通过编程方式添加其他元素。我在xml布局中添加的元素没有显示在屏幕上。 它们是否可能就在我添加到框架布局的曲面视图后面?如果是这样的话,有可能把他们带到前线吗 谢谢你们 “FameLayout设计用于

这有点难以描述,但我会尽全力:

我正在开发一个android应用程序,使用自定义的摄像头活动。在本相机活动中,我使用编程方式创建曲面视图,并将其设置为xml布局文件中定义的framelayout(覆盖全屏)

我现在的问题是,如何向框架布局添加其他元素?仅以编程方式?我这样问是因为到目前为止,我只能通过编程方式添加其他元素。我在xml布局中添加的元素没有显示在屏幕上。 它们是否可能就在我添加到框架布局的曲面视图后面?如果是这样的话,有可能把他们带到前线吗

谢谢你们


“FameLayout设计用于在屏幕上屏蔽一个区域以显示单个项目。通常,FrameLayout应用于保存单个子视图,因为在子视图不重叠的情况下,很难以可扩展到不同屏幕大小的方式组织子视图。但是,您可以使用android:layout\u gravity属性将多个子项添加到FrameLayout,并通过为每个子项指定重力来控制它们在FrameLayout中的位置。“

当然,您可以在
框架布局中添加尽可能多的按钮和其他小部件。由于
FrameLayout
允许堆叠视图,因此您在xml文件中添加的组件现在位于您以编程方式添加的视图后面。以下是如何动态创建和添加小部件:

// find your framelayout
frameLayout = (FrameLayout) findViewById(....);

// add these after setting up the camera view        

// create a new Button
Button button1 = new Button(this);

// set button text
button1.setText("....");

// set gravity for text within button
button1.setGravity(Gravity.....);

// set button background
button1.setBackground(getResources().getDrawable(R.drawable.....));

// set an OnClickListener for the button
button1.setOnClickListener(new OnClickListener() {....})

// declare and initialize LayoutParams for the framelayout
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT);

// decide upon the positioning of the button //
// you will likely need to use the screen size to position the
// button anywhere other than the four corners
params.setMargins(.., .., .., ..);

// use static constants from the Gravity class
params.gravity = Gravity.CENTER_HORIZONTAL;

// add the view
fl1.addView(button2, params);

// create and add more widgets

....
....
编辑1:

这里有一个技巧你可以使用:

// Let's say you define an imageview in your layout xml file. Find it in code:
imageView1 = (ImageView) findViewById(....);

// Now you add your camera view.
.........

// Once you add your camera view to the framelayout, the imageview will be 
// behind the frame. Do the following:
framelayout.removeView(imageView1);
framelayout.addView(imageView1);

// That's it. imageView1 will be on top of the camera view, positioned the way
// you defined in xml file
这是因为:

子视图绘制在堆栈中,最新添加的子视图位于顶部(来自FrameLayout上的android资源页)


android:layout\u gravity
属性对我没有帮助。我的框架布局中仍然不能有多个元素。建议不要在框架布局中使用多个项目。你还想违背这个建议吗?那么你认为动态添加元素是唯一的方法吗?@user2426316否。请参见上面的编辑1。