import android.content.Context;import android.text.Editable;import android.text.SpannableString;import android.text.TextWatcher;import android.text.style.UnderlineSpan;import android.util.AttributeSet;import android.widget.TextView;
/*** Created with IntelliJ IDEA.* User: Justin* Date: 9/11/13* Time: 1:10 AM*/public class UnderlineTextView extends TextView{private boolean m_modifyingText = false;
public UnderlineTextView(Context context){super(context);init();}
public UnderlineTextView(Context context, AttributeSet attrs){super(context, attrs);init();}
public UnderlineTextView(Context context, AttributeSet attrs, int defStyle){super(context, attrs, defStyle);init();}
private void init(){addTextChangedListener(new TextWatcher(){@Overridepublic void beforeTextChanged(CharSequence s, int start, int count, int after){//Do nothing here... we don't care}
@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count){//Do nothing here... we don't care}
@Overridepublic void afterTextChanged(Editable s){if (m_modifyingText)return;
underlineText();}});
underlineText();}
private void underlineText(){if (m_modifyingText)return;
m_modifyingText = true;
SpannableString content = new SpannableString(getText());content.setSpan(new UnderlineSpan(), 0, content.length(), 0);setText(content);
m_modifyingText = false;}}
现在……每当您想在XML中创建下划线文本视图时,只需执行以下操作:
<com.your.package.name.UnderlineTextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:gravity="center"android:text="This text is underlined"android:textColor="@color/blue_light"android:textSize="12sp"android:textStyle="italic"/>
public class UnderLineTextView extends TextView {
public UnderLineTextView(Context context) {super(context);this.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);}
public UnderLineTextView(Context context, @Nullable AttributeSet attrs) {super(context, attrs);this.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);}
}