Разделитель Android/разделитель линии в макете?

Я хотел бы нарисовать строку прямо в середине макета и использовать его как разделитель других элементов, таких как TextView. Есть ли хороший виджет для этого. Я не хочу использовать изображение, так как было бы трудно сопоставить другие компоненты с ним. И я хочу, чтобы он был относительно позиционирован. Благодаря

Ответ 1

Я обычно использую этот код для добавления горизонтальной линии:

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"/>

Чтобы добавить вертикальный разделитель, установите значения layout_width и layout_height

Ответ 2

Чтобы улучшить ответы, предоставленные Алекс Кучеренко и Dan Dar3

Я добавил это в мои стили:

<style name="Divider">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">1dp</item>
    <item name="android:background">?android:attr/listDivider</item>
</style>

Тогда в моих макетах меньше кода и проще читать.

<View style="@style/Divider"/>

Ответ 3

Добавьте это в свой макет, где вы хотите делитель (измените атрибуты в соответствии с вашими потребностями):

<ImageView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@android:drawable/divider_horizontal_dark"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scaleType="fitXY"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingBottom="2dp"
    android:paddingTop="2dp" />

Ответ 4

Вы можете использовать это в LinearLayout:

android:divider="?android:dividerHorizontal"
android:showDividers="middle"

Пример:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="?android:dividerHorizontal"
    android:showDividers="middle"
    android:orientation="vertical" >            

        <TextView 
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:text="abcd gttff hthjj ssrt guj"/>

        <TextView 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="abcd"/>
        <TextView 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="abcd gttff hthjj ssrt guj"/>

        <TextView 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="abcd"/>

</LinearLayout>

Ответ 5

<TextView
    android:id="@+id/line"
    style="?android:attr/listSeparatorTextViewStyle"
    android:paddingTop="5dip"
    android:gravity="center_horizontal"
    android:layout_below="@+id/connect_help"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#000" />

Ответ 6

используйте этот код. Это поможет

<LinearLayout
    android:layout_width="0dip"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:layout_weight="1"
    android:divider="?android:dividerHorizontal"
    android:gravity="center"
    android:orientation="vertical"
    android:showDividers="middle" >

Ответ 7

У меня есть самый простой способ добавить разделитель.

Вертикальный разделитель:

<View style="@style/dividerVertical"/>

Vertical divider view

Горизонтальный разделитель:

<View style="@style/dividerHorizontal"/>

Horizontal divider view

Это все да!

Просто поместите это в res>values>styles.xml

<style name="dividerBase">
    <item name="android:background">?android:attr/listDivider</item> //you can give your color here. that will change all divider color in your app.
</style>

<style name="dividerHorizontal" parent="dividerBase">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">1dp</item> // You can change thickness here.

</style>

<style name="dividerVertical" parent="dividerBase">
    <item name="android:layout_width">1dp</item>
    <item name="android:layout_height">match_parent</item>
</style>

Ответ 8

если вы используете actionBarSherlock, вы можете использовать класс com.actionbarsherlock.internal.widget.IcsLinearLayout, чтобы поддерживать разделители и показывать их между представлениями.

пример использования:

<com.actionbarsherlock.internal.widget.IcsLinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:divider="@drawable/divider"
    android:dividerPadding="10dp"
    android:orientation="vertical"
    android:showDividers="beginning|middle|end" >
... children...

res/drawable/divider.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <size android:height="2dip" />

    <solid android:color="#FFff0000" />

</shape>

Обратите внимание, что по какой-то причине предварительный просмотр в графическом дизайнере говорит "android.graphics.bitmap_delegate.nativeRecycle(I) Z". не уверен, что это значит, но его можно игнорировать, так как он отлично работает на обеих версиях андроида и старых (проверен на Android 4.2 и 2.3).

кажется, что ошибка отображается только при использовании API17 для графического дизайнера.

Ответ 9

Просто напишите это:

 android:divider="?android:dividerHorizontal"
 android:showDividers="middle"

полный пример:

<LinearLayout
        android:id="@+id/llTipInformation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvServiceRating"
        android:orientation="horizontal"
        android:divider="?android:dividerHorizontal"
        android:layout_marginTop="@dimen/activity_horizontal_margin"
        android:showDividers="middle">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="@string/main.msg.tippercent"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@color/colorWhite"
            android:layout_marginTop="@dimen/activity_vertical_margin"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="@string/main.msg.tiptotal"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@color/colorWhite"
            android:layout_marginTop="@dimen/activity_vertical_margin"/>

</LinearLayout>

Ответ 10

Добавление этого представления; который рисует разделитель между вашим textviews

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#000000" />

Ответ 11

Вот ваш ответ. Это пример рисования линии между элементами управления...

<TextView
            android:id="@+id/textView1"
            style="@style/behindMenuItemLabel1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="1dp"
            android:text="FaceBook Feeds" />

         <View
             android:layout_width="fill_parent"
             android:layout_height="2dp"
             android:background="#d13033"/>

         <ListView
            android:id="@+id/list1"
            android:layout_width="350dp"
            android:layout_height="50dp" />

Этот код нарисовать линию между двумя элементами управления...

Ответ 12

Это очень просто. Просто создайте вид с черным цветом фона.

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#000"/>

Это создаст горизонтальную линию с цветом фона. Вы также можете добавить другие атрибуты, такие как поля, paddings и т.д., Как и любое другое представление.

Ответ 13

Он добавляет горизонтальный разделитель в любом месте вашего макета.

    <TextView
       style="?android:listSeparatorTextViewStyle"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"/>

Ответ 14

Версия выполнения:

View dividerView = new View(getContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
    ViewGroup.LayoutParams.FILL_PARENT, UIUtils.dpToPix(getContext(), 1));
dividerView.setLayoutParams(lp);

TypedArray array = getContext().getTheme()
    .obtainStyledAttributes(new int[] {android.R.attr.listDivider});
Drawable draw = array.getDrawable(0);       
array.recycle();

dividerView.setBackgroundDrawable(draw);
mParentLayout.addView(dividerView);

Ответ 15

<View
            android:layout_width="2dp"
            android:layout_height="match_parent"
            android:layout_marginTop="4dp"
            android:background="@android:color/darker_gray" />

Между двумя макетами Поместите этот код, чтобы получить Divider.

Ответ 16

//for vertical line:

<View
   android:layout_width="1dp"
   android:layout_height="fill_parent"
   android:background="#00000000" />




//for horizontal line: 

<View
   android:layout_width="fill_parent"
   android:layout_height="1dp"
   android:background="#00000000" />
//it works like a charm

Ответ 17

используйте этот xml-код для добавления вертикальной линии

 <View
    android:layout_width="1dp"
    android:layout_height="match_parent"
    android:layout_centerVertical="true"
    android:background="#000000" />

используйте этот xml-код для добавления горизонтальной строки

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#000000" />

Ответ 18

Вы можете использовать этот элемент <View> сразу после первого TextView.

 <View
         android:layout_marginTop="@dimen/d10dp"
         android:id="@+id/view1"
         android:layout_width="fill_parent"
         android:layout_height="1dp"
         android:background="#c0c0c0"/>

Ответ 19

В тех случаях, когда вы используете свойство android:layout_weight для назначения доступного пространства экрана компонентам компоновки, например

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:orientation="vertical">
        ...
        ...
    </LinearLayout>

     /* And we want to add a verical separator here */

    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:orientation="vertical">
        ...
        ...
     </LinearLayout>

</LinearLayout>

Чтобы добавить разделитель между существующими двумя макетами, которые уже заняли все пространство экрана, мы не можем просто добавить еще один LinearLayout с android:weight:"1" потому что это сделает три столбца равной ширины, которые нам не нужны. Вместо этого мы уменьшим объем пространства, которое мы предоставим этому новому макету. Окончательный код будет выглядеть так:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:orientation="vertical">
        ...
        ...
    </LinearLayout>

                    /* *************** ********************** */

    /* Add another LinearLayout with android:layout_weight="0.01" and 
       android:background="#your_choice" */
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.01"
        android:background="@android:color/darker_gray"
     />

    /* Or View can be used */
    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:layout_marginTop="16dp"
        android:background="@android:color/darker_gray"
     />

                     /* *************** ********************** */

    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:orientation="vertical">
        ...
        ...
    </LinearLayout>

</LinearLayout>

enter image description here

Ответ 20

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="2dp"
    android:scaleType="fitXY"
    android:src="?android:attr/listDivider" />

Ответ 21

Если вы собираетесь использовать его много, лучше всего

styles.xml:

<style name="Seperator">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">1dp</item>
        <item name="android:background">@color/light_color</item>
    </style>

теперь в вашем макете, просто добавьте его как:

<View style="@style/Seperator" />

Ответ 22

Я обычно использую этот код:

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:background="#aa000000" />

если у вас есть объект в вашем макете, и вы хотите установить строку ниже, которая использует этот атрибут в ImageView:

android:layout_below="@+id/textBox1"

Ответ 23

Это поможет вам решить эту проблему. Здесь создается небольшой вид, чтобы сделать черную линию разделителем между двумя видами.

 <View
        android:layout_width="3dp"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
         />

Ответ 24

Добавьте горизонтальную черную линию, используя следующую команду:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#000000"
    android:layout_marginTop="10dp"/>

Ответ 25

Чтобы выполнить ответ Camille Sévigny, вы можете дополнительно определить свою собственную форму линии, например, чтобы настроить цвет линии.

Определите форму xml в каталоге с возможностью рисования. line_horizontal.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" android:shape="line">
    <stroke android:width="2dp" android:color="@android:color/holo_blue_dark" />
    <size android:width="5dp" />
</shape>

Используйте эту строку в своем макете с желаемыми атрибутами:

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingTop="2dp"
        android:src="@drawable/line_horizontal" />

Ответ 26

Вот код "горизонтальная разделительная линия между двумя текстовыми представлениями". Попробуй это

    <TextView
        android:id="@id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="5dp"
        android:inputType="textPersonName"
        android:text:"address" />


    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/black"/>


    <TextView
        android:id="@id/textView7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName" 
        android:text:"Upload File" />/>

Ответ 27

Простое решение

просто добавьте этот код в свой макет и замените 'Id_of__view_present_above' на идентификатор представления, ниже которого вам нужен разделитель.
<TextView
  android:layout_width="match_parent"
  android:layout_height="1dp"
  android:background="#c0c0c0"
  android:id="@+id/your_id"
  android:layout_marginTop="16dp" 
  android:layout_below="@+id/Id_of__view_present_above"
/>

Ответ 28

Разделите пространство на две равные части:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:divider="?android:dividerHorizontal"
        android:showDividers="end"></LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"></LinearLayout>

</LinearLayout>

Обратите внимание, что одна часть содержит разделитель в конце

Ответ 29

Например, если вы использовали recyclerView для своих товаров:

в файле build.gradle:

dependencies {
    compile 'com.yqritc:recyclerview-flexibledivider:1.4.0'

Если вы хотите установить значения цвета, размера и поля, вы можете указать следующее:

RecyclerView recyclerView = (RecyclerView) 
findViewById(R.id.recyclerview);
recyclerView.addItemDecoration(
        new HorizontalDividerItemDecoration.Builder(this)
                .color(Color.RED)
                .sizeResId(R.dimen.divider)
                .marginResId(R.dimen.leftmargin, R.dimen.rightmargin)
                .build());

Ответ 30

<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<item
    android:bottom="0dp"
    android:left="-2dp"
    android:right="-2dp"
    android:top="-2dp">
    <shape android:shape="rectangle">
        <stroke
            android:width="1dp"
            android:color="@color/divider" />
    </shape>
</item>