我需要允许用户在+之后输入电话号码,我如何在编辑文本中添加此"+".用户无法编辑+.用户可以输入数字,然后输入+.通过使用editText.setText("+");它仍然允许用户编辑此+.如何使此文本不可编辑.
使用您的类自定义EditText.
找到以下示例代码以供参考.
public class CustomEdit extends EditText {
private String mPrefix = "+"; // can be hardcoded for demo purposes
private Rect mPrefixRect = new Rect(); // actual prefix size
public CustomEdit(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
mPrefixRect.right += getPaint().measureText(" "); // add some offset
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), getPaint());
}
@Override
public int getCompoundPaddingLeft() {
return super.getCompoundPaddingLeft() + mPrefixRect.width();
}
}
Run Code Online (Sandbox Code Playgroud)
在xml中使用如下
<com.example.CustomEdit
android:id="@+id/edt_no"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/edit_gray"
android:textSize="@dimen/text_14sp"
android:inputType="number"
android:maxLength="10"
>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2569 次 |
| 最近记录: |