2012-02-01 32 views
2

我在main.xml中定義的RelativeLayout的:設定位置編程

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 
</RelativeLayout> 

並添加編程中的onCreate一個TextView和EditText上:

public void onCreate(Bundle savedInstanceState){ 
setContentView(R.layout.main); 

addContentView(customGlView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); 

addContentView(myTextView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
addContentView(myEditText, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
} 

他們都出現,但在左上角重疊。我花了好幾個小時才弄清楚如何將它們放置在彼此的下方,或者一個放在屏幕的左下角,另一個放在右下角。如果我通過main.xml添加它們,它們都不會顯示出來。任何人都可以給我一個正確的方向提示嗎?

回答

1

規則添加到您的LayoutParams將設置下面的另外一個TextView的..

RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 

TextView tv1 = new TextView(this); 
tv1.setId(1); 
tv1.setText("myTextView"); 

params1.addRule(RelativeLayout.BELOW, tv1.getId()); 
TextView tv2 = new TextView(this); 
2

對於RelativeLayout,你需要指定元素的相對位置,使用LayoutParams

myTextView.setId(1); 
myEditText.setId(2); 

addContentView(myTextView, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 

final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) 
params.addRule(RelativeLayout.BELOW, myTextView.getId()); 
addContentView(myEditText, params); 
+0

這不起作用。我已經通過setId()爲兩個視圖分配了ID,就像在Raoul Georges的答案中一樣,但它們仍然是相互重疊的。 – Lennart 2012-02-01 11:02:17

+1

嗯,很奇怪。你確定你使用了不同的LayoutParams變量嗎?如果你重複使用相同的結果,你會得到不可預知的結果 – Guillaume 2012-02-01 11:14:39

+0

是的,我爲每一個使用了一個不同的LayoutParams。一個是BELOW,另一個是ABOVE。 – Lennart 2012-02-01 11:20:07

0

我無法用RelativeLayout解決這個問題,但是使用LinearLayout完全符合你想要做的。

addView(myEditText); 

或者您可以使用this method將它們添加到您想要的任何位置。例如,您可以先添加myEditText,然後在myEditText上添加myTextView:

addView(myEditText); 
addView(myTextView, 0); 
相關問題