程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> android-設置布局的水平垂直中心

android-設置布局的水平垂直中心

編輯:編程綜合問答
設置布局的水平垂直中心

在XML布局文件中有scrollview

<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>

需要一個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);

最佳回答:


修改XML文件:
添加fillViewporttrue

<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"
   >

刪除不必要的布局。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved