4

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

Yury
  • 20,618
  • 7
  • 58
  • 86
Tim Wong
  • 277
  • 1
  • 4
  • 17

2 Answers2

4

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);
            }
        }               
    }
});
Taras Feschuk
  • 689
  • 1
  • 6
  • 8
0

You can use this way (prepend your hint with required number of spaces). Add this to your customized EditText class:

@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
}
kinORnirvana
  • 1,667
  • 2
  • 17
  • 22