Android drawing separator / separator in layout?

Keywords: Android xml less encoding

I want to draw a line in the middle of the layout and use it as a separator for other items such as TextView. Is there a good widget. I really don't want to use images because it's hard to match other components to it. I hope it can also be relatively positioned. Thank you

#1 building

I usually use this code to add horizontal lines:

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

To add a vertical separator, toggle the value of layout? Width and layout? Height

#2 building

Improvement Alex Kucherenko and Dan Dar3 Answers provided

I add this to my style:

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

Then I have less code in my layout and easier reading.

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

#3 building

Runtime version:

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

#4 building

To complete CamilleS é vigny's answer, you can also define your own line shape, such as custom line color.

Define the XML shape in the drawable directory. line_horizo​​ntal.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>

Use this row in the layout with the required properties:

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

#5 building

Use this code. I'll help you

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

Posted by dzm on Sat, 28 Dec 2019 09:22:34 -0800