You can do this programmatically, in Java code. For instance:
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; } });
Do not miss the word "final". This makes your text visible in the listener code.
Instead of the final keyword, you can use `View v` in` TextView` in the onKey method.
Updated March 9, 2012:
In this case, you can remove the `onKeyListener` and write` onFocusChangeListener`
Here is the 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); } } } });
source share