横线在不同的场景中有不同的表示方式,在Android中绘制横线可以通过以下几种方式:
1. 使用View自定义控件:可以继承自View或者其子类,重写onDraw方法,在onDraw方法中使用Canvas绘制横线。
```java
public class LineView extends View {
private Paint mPaint;
public LineView(Context context) {
super(context);
init();
}
public LineView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public LineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeWidth(5);
mPaint.setColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float startX = 0;
float startY = getHeight() / 2;
float stopX = getWidth();
float stopY = getHeight() / 2;
canvas.drawLine(startX, startY, stopX, stopY, mPaint);
}
}
```
在布局文件中使用该自定义控件`LineView`即可显示一条横线:
```xml
> android:layout_width="match_parent" android:layout_height="2dp" />
```
2. 使用View的background属性:可以直接在布局文件中使用View的background属性设置横线的颜色和高度。
```xml
> android:layout_width="match_parent" android:layout_height="2dp" android:background="#000000" />
```
3. 使用ImageView:可以在ImageView中设置一张纯色的横线图片作为背景,通过调整ImageView的宽和高来控制横线的长度和厚度。
```xml
> android:layout_width="match_parent" android:layout_height="2dp" android:src="@drawable/line" />
```
其中,drawable/line.xml为纯色横线图片的定义:
```xml
```
以上是三种常见的在Android中绘制横线的方式,可以选择适合自己的方式进行实现。