On the soft keyboard in Android you can set the soft keyboard to show the numbers instead of a-z keyboard using android:inputType="numberDecimal". However, what do I do if I only want to show the top number row 1 2 3 4 5 6 7 8 9 0 and not the following rows starting with # # $ % ...?
Thanx for listening!
android:inputType="phone"
android:digits="1234567890"
is an option
You must only add this line on your code:
input.setRawInputType(Configuration.KEYBOARD_12KEY);
this will show only the numeric keyboard.
The phone number pad is the closest thing I've found (set inputType="phone" on your EditText).
The accepted answer did not work for me (tested on OnePlus 3t and Samsung Galaxy S6/S7 phones).
This solution uses numberPassword but overrides the default transformation method for the EditText to show characters instead of showing dots.
<EditText
android:id="#+id/userid"
android:inputType="numberPassword"
android:maxLength="6"
/>
// Numeric 6 character user id
EditText input = findViewById(R.id.userid);
// Process input and show characters instead of dots
input.setTransformationMethod(SingleLineTransformationMethod.getInstance());
Just posted an answer here but re-posting for simplicity:
Seems Android has added the functionality we were seeking. This is the xml I use for simple EditText numeric entry:
android:inputType="numberPassword"
android:digits="0123456789"
android:singleLine="true"
android:ems="4"
android:textColor="#android:color/black"
android:gravity="center"
The accepted answer didn't work for me. It kept showing other unwanted characters
I found a way to accomplish the behavior I wanted by changing the inputType to numberPassword and then disabling the password dots
textInput.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
textInput.transformationMethod = SingleLineTransformationMethod()
Last I looked into it, Android did not have any good options for that. I ended up having to write my own version of a soft keyboard-like user interface.
I had implemented this for android in Xamarin. So, my code is in C#. But the principal stays the same. You can set attribute of edittext to android:inputType="numberPassword".
Then within your code you attach custom transformation method to your edittext view.
holder.edtxtQty.TransformationMethod = new HiddenPasswordTransformationMethod();
private class HiddenPasswordTransformationMethod : global::Android.Text.Method.PasswordTransformationMethod
{
public override Java.Lang.ICharSequence GetTransformationFormatted(Java.Lang.ICharSequence source, View view)
{
return new PasswordCharSequence(source);
}
}
private class PasswordCharSequence : Java.Lang.Object, Java.Lang.ICharSequence
{
private char DOT = '\u2022';
private Java.Lang.ICharSequence _source;
public PasswordCharSequence(Java.Lang.ICharSequence source)
{
_source = source;
}
public char CharAt(int index)
{
return _source.CharAt(index);
}
public int Length()
{
return _source.Length();
}
public Java.Lang.ICharSequence SubSequenceFormatted(int start, int end)
{
return _source.SubSequenceFormatted(start, end); // Return default
}
public IEnumerator<char> GetEnumerator()
{
return _source.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _source.GetEnumerator();
}
}
From code:
et.setInputType(InputType.TYPE_CLASS_NUMBER)
Related
I set InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_CLASS_NUMBER to my EditText and i want to use comma for decimal separator. So i set digits "0123456789.," to EditText.
editText.keyListener = DigitsKeyListener.getInstance("0123456789.,")
I set a TextWatcher on EditText to handle user input. When i clicked comma(",") on Android emulator keyboard, it is working as expected but if i get build on my phone, which has Samsung Keyboard, comma key is disabled and doesnt work. I searched so much but i couldn't find a way.
Any idea with this problem?
It's the year 2022, and still this problem exists (at least on Samsung devices):)
So I solved this by adding a TextChangedListener to the EditText and check, whether the last entered character is equal to a (country specific) thousands separator. If so, I replace it by a country specific decimal separator:
public class EditTextTausenderErsetzer implements TextWatcher{
...
#Override
public void afterTextChanged(Editable editable)
{
// determine country specific separators
// char thousandsSep = .., char commaSep =..
int comma_index = editable.toString().indexOf(commaSep);
if(comma_index == -1) { // no comma so far, thus there might be a "." which shall be a comma separator
if (editable.toString().indexOf(thousandsSep) != -1) {
if (editable.toString().indexOf(thousandsSep, (editable.length()-1)) == (editable.length() - 1)) {
editable.delete(editable.length() - 1, editable.length() - 1);
editable.insert(editable.length(), commaSep + "");
}
}
}
// ...
// do other stuff like setting automatically thousands separators
This solution works, if your app manages the thousands separators, and you do not allow the user to set these.
I solved in this way
override fun afterTextChanged(editable: Editable) {
// If the user input from keyboard some special characters like dot, we replace it programmatically with comma
if (editable.toString().contains(".")) {
editable.delete(editable.toString().length - 1, editable.toString().length)
editable.insert(editable.toString().length, ",")
return
} }
I am working on Android Smart TV application:
In a view there is a custom keyboard and an EditText.
When application launches focus goes to the keyboard.
Desired:
When the user types with keyboard (clicking with a remote) the cursor should also blink inside the editText.
How can I show this effect inside the EditText?
This happens if you set a background for the field. If you want to solve this, set the cursorDrawable to #null.
You should add textCursorDrawable with cursorVisible.
Reference to a drawable that will be drawn under the insertion cursor.
android:cursorVisible="true"
android:textCursorDrawable="#null"
You could try something like this:
editText.setText(text);
editText.setPressed(true);
editText.setSelection(editText.getText().length()); // moves the cursor to the end of the text
However, there are 2 problems with this approach:
The cursor will not blink. The logic for the blinking is in the Editor class and cannot be overridden. It requires that the EditText is focused, and only 1 View can be focused at once within a Window - in your case that will be one of the keyboard buttons.
/**
* #return True when the TextView isFocused and has a valid zero-length selection (cursor).
*/
private boolean shouldBlink() {
if (!isCursorVisible() || !mTextView.isFocused()) return false;
...
}
The cursor will not always be visible. The blinking of the cursor is based on the System time - it is visible for half a second, and hidden for the next half a second. The cursor will only be visible if the code I suggested above is called at a point in time when the cursor would be visible according to the System time.
This is why the native keyboard/IME works the way it does. It is a separate Window that allows the EditText to maintain focus and have the blinking cursor functionality, while the user is tapping on Views in a different Window (the keyboard/IME).
That being said, there is a workaround for the problems above - make sure to set shouldBlink to false when you no longer need it though, it's a guaranteed memory leak or crash otherwise:
private void blink() {
if (shouldBlink) {
editText.setText(editText.getText());
editText.setPressed(true);
editText.setSelection(editText.getText().length());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (shouldBlink) {
blink();
}
}
}, 500);
}
}
You can do this..I hope/think that u have a layout for the buttons u have created, by this u can set a Focus Listener for that layout and inside the onFocusChange method you can check if(layout.hasFocus()) and do this...
For example if your editText is named as et, u can set this to it:
et.setActivated(true);
et.setPressed(true);
I have a small example code for you having two edit text
et2.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(et2.hasFocus()){
//et1.setCursorVisible(true);
et1.setActivated(true);
et1.setPressed(true);
}
}
});
In your layout xml file add the following line in your edit text:
<requestFocus/>
This will place the cursor in your editText widget.
Hope it helps.
simply add
editText.requestFocus();
There is a couple of ways doing it:
1) XML
android:cursorVisible="true"
2) Java
mEditText.setOnClickListener(editTextClickListener);
OnClickListener editTextClickListener = new OnClickListener() {
public void onClick(View v) {
if (v.getId() == mEditText.getId()) {
mEditText.setCursorVisible(true);
}
}
};
or
if (mEditText.hasFocus()){
mEditText.setCursorVisible(true);
}
I know this is necro, but this was much better than the solutions above. Just extend EditText and add:
#Override
public boolean isCursorVisible() {
return true;
}
#Override
public boolean isFocused() {
return true;
}
And in your XML:
<com.foo.MyEditText
...
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
android:cursorVisible="true"/>
Now the EditText thinks it is focused and the cursor is visible, but it actually can't be focused.
private void setFocusCursor(){
mBinding.replyConversationsFooter.footerEditText.setFocusable(true);
`mBinding.replyConversationsFooter.footerEditText.setFocusableInTouchMode(true);`
`mBinding.replyConversationsFooter.footerEditText.requestFocus();`
}
Just call this function in oncreateView() and there you go.
We can only set one and only focus on a window.So doing this will help you solve your problem.
You can use the following code in your Activity:
//Get the EditText using
EditText et = (EditText)findViewById(R.id.editText);
//Set setCursorVisible to true
et.setCursorVisible(true);
You can explicitly put caret to last position in text:
int pos = editText.getText().length();
editText.setSelection(pos);
This will always focus on first character on edittext.
android:focusable="true"
Tested on API 27, 28 emulator.
Remove a background attribute, add focusable:
<EditText
...
android:focusable="true"
android:focusableInTouchMode="true"
/>
In code write: edit.requestFocus(); Though an underline will be visible.
In order to remove an underline, see https://stackoverflow.com/a/52052087/2914140:
edit.getBackground().mutate().setColorFilter(ContextCompat.getColor(getContext(), R.color.white), PorterDuff.Mode.SRC_ATOP);
To change a color of the cursor see https://stackoverflow.com/a/49462015/2914140:
add android:textCursorDrawable="#drawable/shape_cursor", while shape_cursor is:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<size
android:width="1dp"
android:height="25dp"
/>
<solid android:color="#color/gray" />
</shape>
It works on API 27, 28 emulator, but on a real device (API 21) cursor disappears. I tried many variants from here and there, but nothing helped.
Then I noticed that when EditText contains at least one symbol, it shows cursor. I added a TextWatcher to add a space when nothing entered.
private lateinit var someText: String
...
edit.requestFocus()
edit.setText(" ")
edit.addTextChangedListener(YourTextWatcher())
private inner class YourTextWatcher : TextWatcher {
override fun afterTextChanged(s: Editable?) {
someText = s.toString().trim()
if (someText.isEmpty()) {
// To not fall into infinite loop.
if (s?.length != 1) {
edit.setText(" ")
}
} else {
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
}
Also you can add paddings in order to tap inside EditText, if it is small.
I did like this:
var msgEditText = dialog.findViewById(R.id.msg1textView) as EditText
msgEditText.isActivated = true
msgEditText.isPressed = true
msgEditText.requestFocus()
msgEditText.setSelection(view.getText().length)
I build EditText dynamically. Among other things, I set 2 properties: hint(.setHint) and inputType(.setInputType). My problem: when I invoke setInputType, setHint has no effect: blank edittexts remain blank with no hint. Once I comment out setInputType, I see all hints. I need both input type and hint. What to do? My code:
private EditText buildTextBox(Property property)
{
EditText control = new EditText(this);
control.setInputType(getInputTypeByPropertyInputType(property.getType()));// android.text.InputType.
control.setHint(property.getDisplayName());
return control;
}
private int getInputTypeByPropertyInputType(String type)
{
if (type.equals("integer"))
{
return android.text.InputType.TYPE_CLASS_NUMBER;
}
else
{
return android.text.InputType.TYPE_CLASS_TEXT;
}
}
#Eugene
Ensure you call control.SetHint() just before you call the control.setGravity() and control.setInputType(); and it works for me verrry much!
column1 = new EditText(this);
column1.setId(i);
column1.setHint("Value");
column1.setInputType(InputType.TYPE_CLASS_NUMBER);
column1.setGravity(Gravity.RIGHT);
I agree with Eugene.
Remove the gravity(just don't use CENTER) and the hint texts will come back as normal.
Nice find!
how to force the EditText to accept only numbers.?
Use android:inputType="number" in your layout XML
This also works fine:
android:digits="0123456789"
Or you can add the following:
yourEditText.setInputType(InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_FLAG_DECIMAL |
InputType.TYPE_NUMBER_FLAG_SIGNED);
this will accept numbers, float point numbers and
negative numbers you can remove any of these as needed
You can use android:inputType="number" in the XML file. You can specify other values such as numberDecimal as well.
Also, you might additionally want to use android:singleLine="true" for a single line Edittext.
Also, look into android:numeric and android:maxLength. maxLength in particular can be useful for setting length limitations.
If you need support for decimal numbers use this:
android:inputType="numberDecimal"
This is the final solution:
public static void enforceEditTextUseNumberOnly(EditText field) {
Typeface existingTypeface = field.getTypeface();
field.setInputType((InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD));
field.setTransformationMethod(new NumericKeyBoardTransformationMethod());
field.setTypeface(existingTypeface);
if (field.getParent().getParent() instanceof TextInputLayout) {
((TextInputLayout) field.getParent().getParent()).setPasswordVisibilityToggleEnabled(false);
}
}
private static class NumericKeyBoardTransformationMethod extends PasswordTransformationMethod {
#Override
public CharSequence getTransformation(CharSequence source, View view) {
return source;
}
}
I've opened a bug but i was wondering if anyone encountered this issue and knows a workaround.
If you define a text view with a hint inside it, give it right gravity (android:gravity="right") then if you define android:singleLine=true or android:maxLines="1" or android:scrollHorizonatally="true" you don't see the hint. removing the right gravity returns the hint to the left side, removing all the tree params i mentioned above puts the hint on the right side. i want my hint on the right, but i need a single horizontal line...
here's the sample layout that doesn't show the hint:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<EditText android:layout_width="fill_parent"
android:layout_gravity="center_vertical|right"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:textSize="16sp"
android:paddingRight="5dp"
android:id="#+id/c"
android:gravity="right"
android:hint="hello!!!"
android:scrollHorizontally="true"
android:maxLines="1"
android:singleLine="true"/>
</LinearLayout>
i checked on 1.6 and 2.1 emulators and it reproduces 100%, i'm prettysure it's a bug, i don't see the connection between single line and the hint.... what's more the hint got it's own layout in the TextView (mLayout and mHintLayout both exists, in onDraw if the text length is 0 mHintLayout if mHint is not null is used).
Did you try android:ellipsize="start"? This has worked great for me in the past when I've wanted my hint and EditText to be centered.
Looks like you're exactly right with the issue; I tried playing with your example layout and saw the same issue. I assume this is your bug report.
The easiest solution is to just change your layout, but that's probably not what you want to do. My first attempt at a work around would be to try not setting any of those three attributes in XML and then setting them in Java. If that doesn't work...
One option is to mimic the hint by either extending the EditText class and attempting to fix the code that lays out the hint yourself, or by overriding the onDraw method to create the hint, or perhaps by simply overlapping a regular TextView on top of the EditText, which you then show/hide manually. You could even have the view check if it's empty, and if so set the text to your hint text and change the color. When the view gains focus, check if its text is equal to your hint and, if so, remove the text and change the color back.
Another possible workaround that's a bit more "hacky" is to leave off the three attributes that cause problems, but try to manually prevent a newline from being created. You'd need to create an OnKeyListener for your EditText, something like this:
editText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
// do nothing
return true;
}
return false;
}
});
You would also want to call editText.setImeOptions(EditorInfo.IME_ACTION_NEXT) to avoid showing the return key. It still may be possible to create a newline in your text field by pasting into it or perhaps some other method, so you would also want to parse and remove newlines when the form is submitted just to be safe. This is also not likely to do what you want as far as horizontal scrolling.
use these properties with hint and single line...u can chnge gravity!!
android:gravity="right"
android:ellipsize="start"
android:imeOptions="actionNext"
android:singleLine="true"
Noting worked good enough for me. When I set Gravity.right, the cursor was always on the right and couldn't be placed in the middle of the word.
I tried a different approach - put the set the gravity the the right when there is no text (or left, if it works for you) and let android decide the best direction once the user entered something
This worked for me:
create TextWatcher class
private static class FilterTextWatcher implements TextWatcher {
private WeakReference<Activity> mActivity;
public FilterTextWatcher(Activity activity) {
mActivity = new WeakReference<Activity>(activity);
}
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (mActivity.get() == null)
return;
EditText searchTxtBx = mActivity.get().mSearchTxtBx;
if (searchTxtBx.getText().toString().length() == 0)
searchTxtBx.setGravity(Gravity.RIGHT);
else
searchTxtBx.setGravity(0);
}
}
use it as class member
private TextWatcher mFilterTextWatcher = new FilterTextWatcher(this);
in onCreate():
mSearchTxtBx.addTextChangedListener(mFilterTextWatcher);
in onDestroy():
mSearchTxtBx.removeTextChangedListener(mFilterTextWatcher);
mFilterTextWatcher = null;
What do you think about my solution to this problem?
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus == false && StringUtils.isNotBlank(editText.getText().toString())) {
editText.setGravity(Gravity.RIGHT);
}
}
});
And the corresponding XML File:
<EditText android:id="#+id/the_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="number" android:hint="#string/edit_text_prompt"/>
Works fine for me: just one line, no enter-key possible, shows me the hint and when I leave the field after some input was given, the text appears right-aligned.
it worked with me when I added:
android:hint="the hint text ..."
android:singleLine="true"
android:ellipsize="start"
and in my activity i added :
myedittext.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_DOWN){
// do nothing
return true;
}
return false;
}
});
I noticed this issue when my TextView atrs are:
android:singleLine="true"
android:gravity="right"
When I try to Linkify the textview or setMovementMethod(LinkMovementMethod.getInstance()) on that textview, the text is just gone.
android:ellipsize="start"
solved my issue, because I use Arabic text in my app.