Technology Sharing

Android adds a horizontal line

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

In Android, adding a horizontal line can usually be achieved in several ways, the most common of which is usingViewComponent or customDrawableHere is a simple example showing how to add a horizontal rule to a layout file:

useViewComponents

In your layout XML file you can add aViewelement and set its width tomatch_parent(or specific width), height is1dpor2dp(or whatever tiny height you want), and then give it a background color.

  1. <View
  2. android:layout_width="match_parent"
  3. android:layout_height="1dp"
  4. android:background="#000000" /> <!-- 你可以将#000000替换成你想要的颜色 -->

ThisViewelement at the appropriate location in your layout file, it will appear as a horizontal line.

Use CustomDrawable

Although usingViewAs a horizontal line is the easiest way, but you can also create a customDrawableTo achieve more complex horizontal line effects, such as gradients, dotted lines, etc.

For example, if you want to create a gradient horizontal line, you can define a gradientDrawableresource:

  1. <!-- res/drawable/gradient_line.xml -->
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
  3. <gradient
  4. android:angle="0"
  5. android:endColor="#FF0000"
  6. android:startColor="#00FF00"
  7. android:type="linear" />
  8. <size android:height="2dp" />
  9. </shape>

Then, in your layout file, put thisDrawableAs a background set to aView

  1. <View
  2. android:layout_width="match_parent"
  3. android:layout_height="2dp"
  4. android:background="@drawable/gradient_line" />

This way you will get a horizontal line with a gradient effect.

Use in layout

Whichever method you choose to create a horizontal rule, you need to place it in the appropriate location in your layout file. For example, in a verticalLinearLayoutmiddle:

  1. <LinearLayout
  2. android:layout_width="match_parent"
  3. android:layout_height="wrap_content"
  4. android:orientation="vertical">
  5. <TextView
  6. android:layout_width="match_parent"
  7. android:layout_height="wrap_content"
  8. android:text="Some Text Above the Line" />
  9. <!-- 水平线 -->
  10. <View
  11. android:layout_width="match_parent"
  12. android:layout_height="1dp"
  13. android:background="#000000" />
  14. <TextView
  15. android:layout_width="match_parent"
  16. android:layout_height="wrap_content"
  17. android:text="Some Text Below the Line" />
  18. </LinearLayout>

In this example, the horizontal lines are placed between theTextViewUsed as a separator between.