EditText背景仅用于文本?

时间:2016-04-04 05:43:38

标签: android android-edittext

如何使用Android EditText实现此类效果。它看起来像选择的文本,我在API中找不到类似的东西。

这不是视图的背景颜色,而是仅适用于文本的背景颜色。你可以看到它在换行符时是如何停止的,文本行之间有一条细白线。

我尝试使用Spannable,但新的行分隔符未显示它正在选择所有文本而没有任何间隙。

预期

enter image description here

获得性

{{3}}

代码

Spannable spannable = mNote.getText();
spannable.setSpan(new BackgroundColorSpan(ContextCompat.getColor(ThankYouNoteActivity.this, R.color.colorPrimaryDark));, 0, mNote.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

2 个答案:

答案 0 :(得分:1)

authenticationToken

样品

see

public class MyLineBackgroundSpan
    implements LineBackgroundSpan {

private int backgroundColor = 0;
private int padding = 0;

public MyLineBackgroundSpan(int backgroundColor, int padding) {
    this.backgroundColor = backgroundColor;
    this.padding = padding;
}

@Override
public void drawBackground(Canvas c, Paint p, int left, int right, int top, int baseline, int bottom, CharSequence text, int start, int end, int lnum) {
    final int textWidth = Math.round(p.measureText(text, start, end));
    final int paintColor = p.getColor();
    final Paint.FontMetrics fm = p.getFontMetrics();

    // using fontMetrics is to free to lineSpacingExtra or includeFontPadding of TextView attributes.

    RectF rect = new RectF(left - padding,
            baseline + fm.ascent - padding,
            left + textWidth + padding,
            baseline + fm.descent + padding);

    p.setColor(backgroundColor);
    c.drawRect(rect, p);

    p.setColor(paintColor);
}
}

答案 1 :(得分:-1)

在如下所示的可绘制文件夹中创建XML,并根据需要设置颜色。然后为EditText设置背景。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent" /> <!--background color of box-->
        </shape>
    </item>

    <item
        android:top="-2dp"
        android:right="-2dp"
        android:left="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="1dp"
                android:color="#000000" />  <!-- color of stroke -->
        </shape>
    </item>
</layer-list>
相关问题