2013-07-29 77 views
2

這是一些難以描述的問題,但我會盡我所能:是否可以將按鈕添加到以編程方式設置的framelayout?

我正在開發一個使用自定義相機活動的android應用程序。在此攝影機活動中,我使用編程方式創建表面視圖,並將其設置爲在xml佈局文件中定義的framelayout(覆蓋全屏)。

我現在的問題是,我怎樣才能將其他元素添加到框架佈局?只有編程方式?我問,因爲截至目前,我只能以編程方式添加其他元素。我在xml佈局中添加的元素沒有出現在屏幕上。 它可能只是在我添加到框架佈局的表面視圖後面?如果是這樣,是否有可能把他們帶到前面?

謝謝你們!

回答

5

當然,你可以添加儘可能多的按鈕和其他小部件到你有的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 

這是因爲:

子視圖繪製在堆棧中,最近添加的子項位於頂部(來自android r在FrameLayout上的源頁面)

+0

那麼你會說動態添加元素是唯一的方法嗎? – user2426316

+0

@ user2426316否。請參閱上面的**編輯1 **。 – Vikram

0

http://developer.android.com/reference/android/widget/FrameLayout.html

「FameLayout被設計來阻擋在屏幕上的區域來顯示一個單一的項目,一般的FrameLayout應該用於保持單個子視圖,因爲它可以是難以組織子視圖中這種方式可以擴展到不同的屏幕尺寸,而不會讓兒童相互重疊。但是,您可以使用android:layout_gravity屬性爲多個孩子添加一個FrameLayout,並通過爲每個孩子分配重力來控制他們在FrameLayout中的位置。

+0

'android:layout_gravity'屬性不能幫助我。我仍然不能在我的框架佈局中有多個元素。 – user2426316

+0

它建議不要在Framelayout上使用多個項目。你仍然想反對這個建議嗎? – JBuenoJr

相關問題