2015-08-24 96 views
0

請問我該如何將TextView放到屏幕的底部?我發現了一些基於xml的解決方案,但是在java中編寫代碼時沒有任何解決方案Android:我怎樣才能把TextView放到java屏幕的底部

TextView myText= new TextView(this); 
myText.setText("some text"); 

在這種情況下,位置就在左上角。 我的XML是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> 

<TextView android:text="@string/hello_world" android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/textView" /> 
</RelativeLayout> 
+2

發佈您的XML請告訴我們你需要它準確放置在哪裏。 –

+0

我的xml幾乎是空的。我不使用xml或圖形佈局來通過鼠標在此應用程序中放置元素。當我僅使用按鈕(我通過循環動態生成)時,我沒有任何問題。我可以使用AddButtonLayout,但是我找不到像textView那樣的東西。 –

+0

即使您的佈局爲空,我們也需要它,因爲您仍然必須至少引用父視圖才能爲其添加視圖。請張貼它。謝謝。 –

回答

1

做這樣的事情:

RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout); 
TextView textView = (TextView) findViewById(R.id.textView); 
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 

//Choose only one of the following. 

//Add this if you want your myText be below textView. 
params.addRule(RelativeLayout.BELOW, textView); 

//Add this if you want to align your myText to the bottom of the screen. 
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); 

TextView myText= new TextView(this); 
myText.setLayoutParams(params); 
myText.setText("Some Text"); 
relativeLayout.addView(myText); 

其中RelativeLayout的是要視圖添加到它的佈局,讓你有一個ID(android:id="@+id/relativeLayout")添加到該佈局,TextView的是另一種文本視圖在您的佈局。

如果您打算使用LinearLayout,則無需addRule()即可參數。它甚至沒有這種方法,因爲它已經垂直或水平地對齊視圖。

+0

謝謝,它的工作原理。 –

0

完全取決於你添加哪種類型的佈局你textView來。最簡單的方法可能是將您的活動的基本佈局設置爲垂直線性佈局。然後,您可以將兩個佈局疊加在一起。對於頂部的一個,您將寬度設置爲match_parent,高度爲0dp,重量爲1,底部寬度爲match_parent,高度爲wrap_content。然後,只需將您的textView添加到底部佈局,並保持在那裏,您可以執行任何Oi想要的頂部佈局。

爲了得到更好的答案,你真的需要更具體,你也可以嘗試把相對佈局和其他許多事情。

相關問題