0

私たちは簡単なことを試みます。RelativeLayout の水平方向および垂直方向の中央に TextView を表示します。

これは

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

すべての予想に反して、テキストはここの左上に表示されます。

しかし今、まったく無意味な LinearLayout を全体に追加します。

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- First item in a relative Layout cannot be centered  -->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
         >
    </LinearLayout>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

そしてタダァー!必要な場所にテキストが表示されます。TextView の場所を変更せずに LinearLayout の行を削除することはできません。RelativeLayout では、他の項目を中央に配置する前に、いくつかの項目を上下および左右に揃える必要があるようです。

4

1 に答える 1

1

同様の問題?

問題の説明

私は現在、 を使用するために中央に配置する必要がある をRelativeLayout保持するラッピングで同様の問題を抱えています。TextViewandroid:layout_centerInParent="true"

API レベル 21 デバイスまたはエミュレーターでコードを実行すると、テキストが適切に中央揃えで表示されます。

ただし、API レベル 19 で同じコードを実行すると、テキスト ビューが中央ではなく、ラップする RelativeLayout の上部に配置されます。

サンプルプロジェクト

簡単にフォローできるように、https://github.com/hanscapelle/SO-16731025でサンプル プロジェクトを作成しました。git からこのコードをチェックアウトし、Android Studio にインポートするだけで、コードを実行できるはずです。

視覚化

レンダリング用の SDK バージョンを変更するだけで、Android Studio のデザイン プレビューを使用してこの問題をテストすることもできます。

でファイルを開くだけでlayout/with_scrollview.xml、Android Studio のプレビューで視覚化されます。

API レベル 21 の使用:

ここに画像の説明を入力

API レベル 19 を使用した同じレイアウト:

ここに画像の説明を入力

回避策

ScrollViewのラッピング

回避策として、ラッピングの ScrollView を削除すると問題が解決することがわかりました。

役に立たなかったもの

ダミービュー

あなたが提案したように間にダミーLinearLayout(または他のビュー)を追加しても、私の問題は解決しませんでした。

サンプル プロジェクトでは、この手法が画面右側の円に適用されています。

于 2015-03-31T13:56:08.960 に答える