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

2

2 Answers 2

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);
            }
        }               
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks much, but I want the cursor lie on left even I doesn't input anything(length = 0).
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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.