¿Cómo hago una línea punteada / discontinua en Android?

Estoy tratando de hacer una línea punteada. Estoy usando esto ahora mismo para una línea sólida:

LinearLayout divider = new LinearLayout( this ); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 2 ); divider.setLayoutParams( params ); divider.setBackgroundColor( getResources().getColor( R.color.grey ) ); 

Necesito algo como esto, pero salpicado en lugar de sólido. Me gustaría evitar hacer cientos de diseños alternando entre un diseño transparente y un diseño sólido.

Sin código java:

Dibujable / punteado.xml:

 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line"> <stroke android:color="#C7B299" 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" /> 

El efecto de la trayectoria se fija en el objeto de la pintura

 Paint fgPaintSel = new Paint(); fgPaintSel.setARGB(255, 0, 0,0); fgPaintSel.setStyle(Style.STROKE); fgPaintSel.setPathEffect(new DashPathEffect(new float[] {10,20}, 0)); 

Puede crear todo tipo de patrones de puntos mediante el suministro de más números en la matriz int [] que especifica las proporciones de guión y la brecha. Esta es una línea simple, igualmente discontinua.

Esto te ayudara. Creación de líneas punteadas utilizando XML. Cree xml en la carpeta dibujable y dé ese fondo al artículo a que usted desea fijar el borde punteado.

—-> Creación de fondo XML "dashed_border"

 <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape> <solid android:color="#ffffff" /> <stroke android:dashGap="5dp" android:dashWidth="5dp" android:width="1dp" android:color="#0000FF" /> <padding android:bottom="5dp" android:left="5dp" android:right="5dp" android:top="5dp" /> </shape> </item> </layer-list> 

—–> Agregar ese fondo al elemento

 <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/dashed_border"/> 

Crear xml (view_line_dotted.xml):

 <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:bottom="-1dp" android:left="-1dp" android:right="-1dp" android:top="0dp"> <shape android:shape="rectangle"> <stroke android:width="1dp" android:color="#ffff0017" android:dashGap="3dp" android:dashWidth="1dp" /> <solid android:color="@android:color/transparent" /> <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" /> </shape> </item> </layer-list> 

Establecer como fondo de su vista:

 <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@drawable/view_line_dotted" /> 

Lo que hice cuando quería dibujar una línea punteada es definir un dibujable dash_line.xml :

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

Y luego en el diseño sólo definir una vista con el fondo como dash_line . Nota para incluir android: layerType = "software" , de lo contrario no funcionará.

 <View android:layout_width="match_parent" android:layout_height="5dp" android:background="@drawable/dash_line" android:layerType="software" /> 

Tengo la costumbre un dashline que apoye la línea horizontal y vertical del guión. Código abajo:

 public class DashedLineView extends View { private float density; private Paint paint; private Path path; private PathEffect effects; public DashedLineView(Context context) { super(context); init(context); } public DashedLineView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public DashedLineView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { density = DisplayUtil.getDisplayDensity(context); paint = new Paint(); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(density * 4); //set your own color paint.setColor(context.getResources().getColor(R.color.XXX)); path = new Path(); //array is ON and OFF distances in px (4px line then 2px space) effects = new DashPathEffect(new float[] { 4, 2, 4, 2 }, 0); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); paint.setPathEffect(effects); int measuredHeight = getMeasuredHeight(); int measuredWidth = getMeasuredWidth(); if (measuredHeight <= measuredWidth) { // horizontal path.moveTo(0, 0); path.lineTo(measuredWidth, 0); canvas.drawPath(path, paint); } else { // vertical path.moveTo(0, 0); path.lineTo(0, measuredHeight); canvas.drawPath(path, paint); } } } 

He utilizado el siguiente como fondo para el diseño:

 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:width="1dp" android:dashWidth="10px" android:dashGap="10px" android:color="android:@color/black" /> </shape> 

Mediante el uso de esta clase se puede aplicar efecto "descifrado y subrayado" a varias líneas de texto. Para utilizar DashPathEffect tienes que desactivar hardwareAccelerated de tu TextView (aunque DashPathEffect método tiene un problema con texto largo). Puede encontrar mi proyecto de ejemplo aquí: https://github.com/jintoga/Dashed-Underlined-TextView/blob/master/Untitled.png .

Public class Unlunlineline implementa LineBackgroundSpan, LineHeightSpan {

 private Paint paint; private TextView textView; private float offsetY; private float spacingExtra; public DashedUnderlineSpan(TextView textView, int color, float thickness, float dashPath, float offsetY, float spacingExtra) { this.paint = new Paint(); this.paint.setColor(color); this.paint.setStyle(Paint.Style.STROKE); this.paint.setPathEffect(new DashPathEffect(new float[] { dashPath, dashPath }, 0)); this.paint.setStrokeWidth(thickness); this.textView = textView; this.offsetY = offsetY; this.spacingExtra = spacingExtra; } @Override public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v, Paint.FontMetricsInt fm) { fm.ascent -= spacingExtra; fm.top -= spacingExtra; fm.descent += spacingExtra; fm.bottom += spacingExtra; } @Override public void drawBackground(Canvas canvas, Paint p, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int lnum) { int lineNum = textView.getLineCount(); for (int i = 0; i < lineNum; i++) { Layout layout = textView.getLayout(); canvas.drawLine(layout.getLineLeft(i), layout.getLineBottom(i) - spacingExtra + offsetY, layout.getLineRight(i), layout.getLineBottom(i) - spacingExtra + offsetY, this.paint); } } 

}

resultado

Utilice un ShapeDrawable en lugar de un LinearLayout y jugar con dashWidth y dashGap

http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

No sé por qué, pero las respuestas votadas no funcionan para mí. Lo escribo de esta manera y funciona bien.
Definir una vista personalizada:

 public class XDashedLineView extends View { private Paint mPaint; private Path mPath; private int vWidth; private int vHeight; public XDashedLineView(Context context) { super(context); init(); } public XDashedLineView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public XDashedLineView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mPaint = new Paint(); mPaint.setColor(Color.parseColor("#3F577C")); mPaint.setStyle(Paint.Style.STROKE); mPaint.setPathEffect(new DashPathEffect(new float[] {10,10}, 0)); mPath = new Path(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); this.vWidth = getMeasuredWidth(); this.vHeight = getMeasuredHeight(); mPath.moveTo(0, this.vHeight / 2); mPath.quadTo(this.vWidth / 2, this.vHeight / 2, this.vWidth, this.vHeight / 2); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawPath(mPath, mPaint); } } 

Entonces usted puede utilizarlo en su xml:

  <com.YOUR_PACKAGE_NAME.XDashedLineView android:layout_width="690dp" android:layout_height="1dp" android:layout_marginLeft="30dp" android:layout_marginTop="620dp"/> 
FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.