我需要允许用户在+之后输入电话号码,我如何在编辑文本中添加此“+”。用户无法编辑+。用户可以输入数字,然后输入+。
通过使用editText.setText("+");
,它仍然允许用户编辑此+。如何使此文本不可编辑。
答案 0 :(得分:5)
使用您的班级自定义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();
}
}
在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"
>
答案 1 :(得分:0)
使用TextWatcher
即可实现。在TextWatcher
中,您可以处理编辑文本值。看这个Tutorial
答案 2 :(得分:0)
应该是这样的
final EditText edt = (EditText) findViewById(R.id.editText1);
edt.setText("+");
Selection.setSelection(edt.getText(), edt.getText().length());
edt.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
if(!s.toString().contains("+")){
edt.setText("+");
Selection.setSelection(edt.getText(), edt.getText().length());
}
}
});