Textview布局中心在ScrollView中以编程方式垂直和水平

dmn*_*nlk 2 android android-layout

应用程序具有scrollviewXML布局.

<ScrollView
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="5dp"
       >
</ScrollView>
Run Code Online (Sandbox Code Playgroud)

我想textView进入这个scrollView中心.

我试过这个代码,设置水平中心,但垂直顶部..我想两个居中.

LinearLayout l1 = new LinearLayout(getActivity());
            l1.setOrientation(LinearLayout.VERTICAL);
            l1.setGravity(Gravity.CENTER);
            l1.setBackgroundColor(Color.WHITE);
            TextView errorView = new TextView(getActivity());
            LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                    new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            errorView.setText("TextView");
            errorView.setTextColor(Color.BLACK);
            errorView.setLayoutParams(params);
            errorView.setGravity(Gravity.CENTER);
            l1.addView(errorView);
            scrollViewCon.addView(l1, lparams);
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Anu*_*ool 5

如下所示更改xml -
fillViewport添加为true.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="5dp"
    android:fillViewport="true"
   >
Run Code Online (Sandbox Code Playgroud)

删除了相对布局添加部分,因为它不是必需的.