我对 Android 中的 EditText 有疑问。如何设置提示对齐中心但文本左对齐?非常感谢。
我只想让光标位于 EditText 的左侧并提示中心
我对 Android 中的 EditText 有疑问。如何设置提示对齐中心但文本左对齐?非常感谢。
我只想让光标位于 EditText 的左侧并提示中心
You can do it programmatically, in Java code. For example:
final EditText editTxt = (EditText) findViewById(R.id.my_edit_text);
editTxt.setGravity(Gravity.CENTER_HORIZONTAL);
editTxt.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_UP) return false;
if (editTxt.getText().length() > 1) return false;
if (editTxt.getText().length() == 1) {
editTxt.setGravity(Gravity.LEFT);
}
else {
editTxt.setGravity(Gravity.CENTER_HORIZONTAL);
}
return false;
}
});
Don't miss a word 'final'. It makes your textView visible in the listener code.
Instead of 'final' keyword you can cast `View v` into the `TextView` in the 'onKey' method.
Updated 9 March 2012:
In such a case, you can remove `onKeyListener` and write `onFocusChangeListener`
Here is some code:
editTxt.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
editTxt.setGravity(Gravity.LEFT);
}
else {
if (editTxt.getText().length() == 0) {
editTxt.setGravity(Gravity.CENTER_HORIZONTAL);
}
}
}
});
您可以使用这种方式(在提示前加上所需的空格数)。将此添加到您自定义的 EditText 类中:
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
String hint = getContext().getString(R.string.my_hint);
float spaceSize = getPaint().measureText(" ");
float textSize = getPaint().measureText(hint);
int freeSpace = w - this.getPaddingLeft() - this.getPaddingRight();
int spaces = 0;
if (freeSpace > textSize) {
spaces = (int) Math.ceil((freeSpace - textSize) / 2 / spaceSize);
}
if (spaces > 0) {
Log.i(TAG, "Adding "+spaces+" spaces to hint");
hint = prependStringWithRepeatedChars(hint, ' ', spaces);
}
setHint(hint);
}
private String prependStringWithRepeatedChars(/* some args */) {
/// add chars to the beginning of string
}