如何将TextView放置在屏幕底部?我发现了一些基于xml的解决方案,但是用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>

最佳答案

做这样的事情:

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()设置参数。它甚至没有该方法,因为它已经垂直或水平对齐了视图。

10-07 12:23
查看更多