I have a question about EditText in Android. How can I set the hint align center but text align left? Thanks a lot.
I just want to make the cursor locate at left and hint center in 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);
}
}
}
});