Android Custom TextView虚线

时间:2013-08-30 06:55:42

标签: android

我正在尝试从很多天但没有得到任何解决方案。我推荐这个 Android:Draw line on a textview 我试图在文本视图中创建虚线,用它完成,工作正常,但我想添加虚线直到文本视图包含的文本的长度,如果文本视图有一行文本然后它工作正常但是如果文本视图有多行文本然后为文本一半或更少然后屏幕宽度的行然后也出现虚线与我不想.... 我用Paint绘制虚线......请帮帮我.... 在此先感谢

1 个答案:

答案 0 :(得分:2)

依靠您所做的主题,尝试在类LinedEditText的构造函数中编写

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

而不是

mPaint = new Paint();
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setColor(0x800000FF);

修改

再次告诉我,你想这样:

underline the whole of textView

或者这个:

underline each line

修改

MainActivity:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    LayoutParams textViewLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    String text = "Sample Sample Sample Sample Sample Sample Sample Sample Sample Sample";

    LinedEditText et = new LinedEditText(this, null, text);
    et.setText(text);
    et.setLayoutParams(textViewLayoutParams);
    et.setKeyListener(null);

    ll.addView(et);

    this.setContentView(ll);
}

LinedEditText:

public class LinedEditText extends EditText {
private Rect mRect;
private Paint mPaint;
String text;

public LinedEditText(Context context, AttributeSet attrs, String text) {
    super(context, attrs);
    this.text = text;

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

@Override
protected void onDraw(Canvas canvas) {
    Rect r = mRect;
    Paint paint = mPaint;

    int lineCount = getLineCount();
    int size = getLayout().getLineStart(lineCount-1);

    String str = getText().toString().substring(size);

    float densityMultiplier = getContext().getResources().getDisplayMetrics().density;
    float scaledPx = 20 * densityMultiplier;
    paint.setTextSize(scaledPx);
    float i = paint.measureText(str);

    for (int k = 0; k < lineCount-1; k++) {
        int baseline = getLineBounds(k, r);
        canvas.drawLine(r.left, baseline + 2, r.right, baseline + 2, paint);
    }

    int baseline = getLineBounds(lineCount-1, r);
    canvas.drawLine(r.left, baseline + 2, i, baseline + 2, paint);

    super.onDraw(canvas);
}
}