21

私は最近、過去数年間に何度か抱えていた問題に再び遭遇しました。

LinearLayoutとても便利layout managerです。しかし、私が完全に見逃しているのは、単一の XML タグの要素間に特定のスペース (パディングなど) を追加できることです。

1 つのタグとは、LinearLayout の宣言で要素間の間隔を定義できることを意味します (たとえば、垂直 LinearLayout では、このレイアウトの 2 つの要素間の垂直スペース)。

XML タグandroid:layout_marginTopまたは LinearLayout のすべての要素に類似したものを追加することで、それを実行できることはわかっています。

しかし、間隔はすべての要素で同じであるため、1 点だけで定義できるようにしたいと考えています。

これを行う簡単な方法を知っている人はいますか (カスタム LinearLayout などを実装していません)? 私は、コーディングを必要とせずに XML で直接動作するソリューションを好みます。

4

5 に答える 5

19

推奨される方法は、線形レイアウトのすべての要素にスタイルを適用することです

android:style="@style/mystyle"

<style name="mystyle">
      <item name="android:layout_marginTop">10dp</item>
      ... other things that your elements have in common
</style>
于 2012-09-18T00:07:16.357 に答える
1

@Chris-Tulipの答えは本当に役に立ちました-良い練習もありました。

私が行ったように、パッケージ android に「Style」のリソース識別子がないという Eclipse エラーが発生する可能性がある場合は、android 名前空間を追加する必要はありません。

したがって、android:style="xx" はエラーを表示しますが、style="xx" は正しいです。ファンキーですが、そのエラーを抱えている人にとっては、これが役立つかもしれません.

于 2014-06-10T03:48:22.683 に答える
0

単一のアイテム「プロトタイプ」を別のxmlファイルで定義し、そのファイルからアイテムをコードで動的に膨張させ、線形レイアウトに挿入することができます。

次に、親 LinearLayout ではなく、実際のアイテムで間隔を定義し (android:layout_marginTopたとえば)、その間隔は、アイテムを膨張させるときにすべてのアイテムに適用されます。

編集:

コンテナ.xml:

<LinearLayout
    android:id="@+id/parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Your items will be added here -->

</LinearLayout>

item.xml:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="This is my child" />

</LinearLayout>

MyActivity.java:

// Put this in a suitable place in your Java code, perhaps
// in "onCreate" or "onResume" depending on where and how
// you initialize your view. You can, of course inflate
// any number of instances of the item and add them to
// your parent LinearLayout.
LayoutInflater inflater = LayoutInflater.from(context);
View item = inflater.inflate(R.layout.item, null, false);

LinearLayout container = findViewById(R.id.parent);
container.addView(view);

私はコードのテストに力を入れていませんが、そのまま「動作するはず」です:-)

于 2012-09-17T07:49:19.307 に答える