How to Make a Dotted/Dashed Line in Android

How do I make a dotted/dashed line in Android?

Without java code:

drawable/dotted.xml:

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

<stroke
android:color="#FF00FF"
android:dashWidth="10px"
android:dashGap="10px"
android:width="1dp"/>
</shape>

view.xml:

<ImageView
android:layout_width="match_parent"
android:layout_height="5dp"
android:src="@drawable/dotted"
android:layerType="software" />

Effect:
Sample Image

How do I make a dotted/dashed line in Jetpack Compose?

You can simply use a Canvas with the method drawLine applying as pathEffect a PathEffect.dashPathEffect:

    val pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
Canvas(Modifier.fillMaxWidth().height(1.dp)) {

drawLine(
color = Color.Red,
start = Offset(0f, 0f),
end = Offset(size.width, 0f),
pathEffect = pathEffect
)
}

Sample Image

You can also apply the same pathEffect to other method as:

    val stroke = Stroke(width = 2f,
pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f)
)
Canvas(Modifier.fillMaxWidth().height(70.dp)){
drawRoundRect(color = Color.Red,style = stroke)
}

Sample Image

Dotted line XML in Android

Dashed lines are not supported in GL mode. So Add

android:layerType="software"

for e.g.

<ImageView
android:layerType="software" // add here
...

in your xml layout for view or programmatically as

view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

Or Turn off hardware -acceleration like this:

android:hardwareAccelerated="false"

Creating horizontal and vertical dotted lines in android

I found the solution

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="90"
android:toDegrees="90" >

<shape android:shape="line" >
<stroke
android:dashGap="6px"
android:dashWidth="6px"
android:color="#C7B299" />
</shape>

</rotate>

OR

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="90"
android:toDegrees="90"
android:drawable="@drawable/horizontal_line"/>

How to set a rectangular-dashed/dotted-line-outline around partial text in TextView?

Solution 1

1 - Create a drawable for the dashes. Like this:

<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="5dp" />
<solid android:color="@android:color/transparent" />
<stroke
android:color="@android:color/black"
android:dashWidth="20px"
android:dashGap="10px"
android:width="3dp"/>
</shape>

2 - Set it as the background of your text view, it can be just a word.

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp">

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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_shape"
android:padding="4dp"
android:text="world!"/>

</LinearLayout>

The result:

Sample Image

Important note: This solution is going to work only for small text, like show a score in a game or small messagens. It won't adapt to big texts.

Solution 2

If you need a more complex solution that works for big texts, you can use a Spannable.

1 -> Create a custom ReplacementSpan

  public class DashedBorderSpan extends ReplacementSpan {

private Drawable mDrawable;
private int mPadding;


public DashedBorderSpan(Drawable drawable, int padding) {
super();

mDrawable = drawable;
mPadding = padding;
}

@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
RectF rect = new RectF(x - mPadding, top - mPadding, x + measureText(paint, text, start, end) + mPadding, bottom + mPadding);

mDrawable.setBounds((int) rect.left, (int)rect.top, (int)rect.right, (int)rect.bottom);

canvas.drawText(text, start, end, x, y, paint);
mDrawable.draw(canvas);
}

@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
return Math.round(paint.measureText(text, start, end));
}

private float measureText(Paint paint, CharSequence text, int start, int end) {
return paint.measureText(text, start, end);
}
}

2 -> Apply the Spannable

TextView textView = (TextView) findViewById(R.id.textasd);

String hello = "Dashed!";

SpannableStringBuilder stringBuilder = new SpannableStringBuilder();

stringBuilder.append(hello);
stringBuilder.setSpan(new DrawableSpan(getDrawable(R.drawable.dashed_border_shape)),
0,
stringBuilder.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

stringBuilder.append("not dashed... boring");

textView.setText(stringBuilder);

This solution will work for all the cases. It's a better solution, although it is more complicated.

Example
If you would like to use it with a place holder use it like this:

    String someText = "Some Text!";

//R.string.placeholder = Hello: %s
String formatedText = String.format(getString(R.string.placeholder), someText);

SpannableStringBuilder stringBuilderPlaceHolder = new SpannableStringBuilder();
stringBuilderPlaceHolder.append(formatedText);

stringBuilderPlaceHolder.setSpan(new DashedBorderSpan(getDrawable(R.drawable.dashed_border_shape), 10),
formatedText.length() - someText.length(),
formatedText.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

textViewPlaceHolder.setText(stringBuilderPlaceHolder);

Result: Sample Image

This way the span will be set only on your place holder. If you have a more complex holder use the same logic to achieve what you need.

Edit

There's a small problem with the solution 2, but there is a solution.

You must take care with padding of the dashed border drawable. If you use padding in the dashed border, you will need to set padding in the TextView that uses the Span. In the image that the author of the question provided, you can see that the upper and bottom lines got cut (if you increase the padding, the lines will be completly gone), in order to avoid this use padding in your textview. Like this:

<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="30dp"
android:paddingTop="3dp" <!-- This will fix the problem! -->
android:paddingBottom="3dp" <!-- This will fix the problem! -->
android:gravity="center_horizontal"
android:text="blabla"
android:textSize="20sp"/>

This will fix the problem =]
Happy coding!

How to make a rounded dashes or dots for line drawable shape

You can achieve a goal using a custom view and drawing on canvas. Please, try this and adjust sizes/styling for your needs:

public class RoundedDashView extends View {

public enum Orientation {
VERTICAL,
HORIZONTAL
}

private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Path path = new Path();
private Orientation orientation = Orientation.HORIZONTAL;

public RoundedDashView(Context context) {
super(context);
init();
}

public RoundedDashView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}

public RoundedDashView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}

public RoundedDashView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}

private void init() {
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(10);
paint.setColor(Color.GRAY);
paint.setPathEffect(new DashPathEffect(new float[]{20, 25}, 20));
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
path.reset();
if (orientation == Orientation.VERTICAL) {
path.moveTo(getWidth() / 2, 0);
path.quadTo(getWidth() / 2, getHeight() / 2, getWidth() / 2, getHeight());
} else {
path.moveTo(0, getHeight() / 2);
path.quadTo(getWidth() / 2, getHeight() / 2, getWidth(), getHeight() / 2);
}
canvas.drawPath(path, paint);
}

public void setOrientation(Orientation orientation) {
this.orientation = orientation;
invalidate();
}
}

Adding horizontal and vertical dotted lines in android

Try using below code.

horizontal_dashed_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<stroke
android:width="1dp"
android:color="#ff0000"
android:dashWidth="4dp"
android:dashGap="4dp"/>
</shape>

vertical_dashed_line.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="90"
android:toDegrees="90"
android:drawable="@drawable/horizontal_dashed_line"/>

Usage:

<View
android:layout_width="4dp"
android:layout_height="300dp"
android:background="@drawable/horizontal_dashed_line"/>

Checkout below article for more details.

How to create vertical or horizontal dashed lines with Android drawables



Related Topics



Leave a reply



Submit