java 如何将 TextView 放置在屏幕底部

How to place a TextView to the bottom of the screen in java

如何将 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() 您的参数。它甚至没有那个方法,因为它已经垂直或水平对齐视图。