当然,您可以添加尽可能多的按钮和其他小部件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 资源页面)