2016-04-04 39 views
0

如何使用Android EditText實現這樣的效果。它看起來像選定的文本,我無法在API中找到類似的東西。僅用於文本的EditText背景?

這不是視圖的背景顏色,而是僅用於文本的背景顏色。你可以看到它是如何在換行處停下來的,並且在文本行之間有一條細細的白線。

我試過了Spannable,但新行分隔符沒有顯示它選擇的所有文本沒有任何間隙。

預計

​​3210

收購

enter image description here

代碼

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

使用'android.text.style.LineBackgroundSpan' – pskink

+0

檢查此[SO鏈接](http://stackoverflow.com/a/ 10676390/3831557)執行 –

+0

嗨pskink謝謝你的評論你可以詳細說明這個概念作爲這個查詢的答案嗎? – Christ

回答

-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> 
1
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); 
} 
} 

樣品

see

int padding = 10; 

SpannableString spannable = new SpnnableString("..."); 
spannable.setSpan(
     new MyLineBackgroundSpan(ContextCompat.getColor(context, R.color.colorPrimaryDark), padding), 
     0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

textView.setShadowLayer(padding, 0, 0, 0); 
textView.setPadding(padding, padding, padding, padding); 
textView.setText(spannable);