Android EditText tooltip text and text

I have a question about EditText in Android. How to set the tooltip align center , but text align left ? Many thanks.

I just want the cursor to be on the left and the center of the tooltip in EditText

+4
source share
2 answers

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); } } } }); 
+4
source

You can use this method (add a hint with the required number of spaces). Add this to your own 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 } 
0
source

Source: https://habr.com/ru/post/1400342/


All Articles