I put an EditText with inputType="textPassword" in my activity's XML
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter Password"
android:inputType="textPassword"
android:padding="16dp"
android:id="#+id/passwordInput"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Till now there is not any problem and I see circles intead of real password characters:
The interesting part is here. Now if I call setSingleLine() on the EditText in the Activity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
passwordInput.setSingleLine()
}
}
will see that the password characters is surprisingly visible!
Another interesting thing is that this issue will not happen if I put android:singleLine="true" in XML of the EditText.
Note: I know that setting setSingleLine on a password field is useless, but I'm curious why calling this function has such side effect.
I think it is because when you call setSingleLine, textview will change it transformation method from PasswordTransformationMethod to SingleLineTransformationMethod. there is only one transformation method accepted at the time in EditText (which is child of TextView)
you can check the source code here:
setSingleLine()
https://android.googlesource.com/platform/frameworks/base/+/jb-mr0-release/core/java/android/widget/TextView.java#6727
follow through the code fill call function setTransformationMethod
https://android.googlesource.com/platform/frameworks/base/+/jb-mr0-release/core/java/android/widget/TextView.java#1461
Try to set it inside XML:
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"
I can't tell you why setting it programaticaly lead to this strange behavior because I usually do this inside XML and I'm doing this in code just to manipulate Views.
If you want to hide the password, you will:
yourTextView.setTransformationMethod(new PasswordTransformationMethod());
If you want to show the password, you will:
yourTextView.setTransformationMethod(new DoNothingTransformation()), or setTransformationMethod(null)
Method setTransformationMethod is show/hide text
Now, you can check the code of class TextView, Because of EditText extended from TextView.
You will see in the function setSingleLine(), It's call function applySingleLine(singleLine, true, true), This function will set again setTransformationMethod(SingleLineTransformationMethod.getInstance());
This is change your Transformation(show/hide text of EditText):
private void applySingleLine(boolean singleLine, boolean applyTransformation,
boolean changeMaxLines) {
mSingleLine = singleLine;
if (singleLine) {
setLines(1);
setHorizontallyScrolling(true);
// change Transformation
if (applyTransformation) {
setTransformationMethod(SingleLineTransformationMethod.getInstance());
}
} else {
if (changeMaxLines) {
setMaxLines(Integer.MAX_VALUE);
}
setHorizontallyScrolling(false);
if (applyTransformation) {
setTransformationMethod(null);
}
}
}
I am trying to change hint text size programmatically, but I just can't find the right method. I'm using setHintTextAppearance, like it's shown in example, but it works only when input is focused or filled with some data. I tried to set EditText textSize also, but still no luck.
textInputLayout.setHintTextAppearance(Vabaco_TextInputLayout_hint_small);
EditText a = textInputLayout.getEditText();
a.setTextSize(8);
You can change hint text size when it unfocused using reflection like this;
try {
Field filed = TextInputLayout.class.getDeclaredField("mCollapsingTextHelper");
filed.setAccessible(true);
Object helper = filed.get(textInputLayout);
Field f1 = helper.getClass().getDeclaredField("mExpandedTextSize");
f1.setAccessible(true);
f1.set(helper,100);
}
catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
name of mExpandedTextSize may be different according to the dependency version for TextInputLayout. You should check TextInputLayout and CollapsingTextHelper classes for the name of variables.
Hope this helps you.
Reflection solution doesn't work on support:design:28.0.0(mExpandedTextSize-> expandedTextSize). Also, Android Q (and later) doesn't support some non-sdk solutions.
Create your custom layout:
public class CustomTextInputLayout extends TextInputLayout {
public CustomTextInputLayout(Context context) {
super(context);
}
#Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if(child instanceof EditText) {
((EditText)child).setTextSize(16);
}
super.addView(child, index, params);
}
}
If setting the text size programmatically is not required you can try like below,I have disabled TextInputLayout hint,
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:hintEnabled="false">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edittext"
android:hint="yorhint"
android:inputType="text"
android:textColorHint="#color/colorLightBlack"
android:textSize="10sp" />
</android.support.design.widget.TextInputLayout>
If required programmatically you can find edittext by id and set the text size.
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.
When an EditText is in password mode, it seems that the hint is shown in a different font (courrier?). How can I avoid this? I would like the hint to appear in the same font that when the EditText is not in password mode.
My current xml:
<EditText
android:hint="#string/edt_password_hint"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"
android:singleLine="true" />
Changing the typeface in xml didn't work on the hint text for me either. I found two different solutions, the second of which has better behavior for me:
Remove android:inputType="textPassword" from your xml file and instead, in set it in java:
EditText password = (EditText) findViewById(R.id.password_text);
password.setTransformationMethod(new PasswordTransformationMethod());
With this approach, the hint font looks good but as you're typing in that edit field, you don't see each character in plain text before it turns into a password dot. Also when making input in fullscreen, the dots will not appear, but the password in clear text.
Leave android:inputType="textPassword" in your xml. In Java, ALSO set the typeface and passwordMethod:
EditText password = (EditText) findViewById(R.id.register_password_text);
password.setTypeface(Typeface.DEFAULT);
password.setTransformationMethod(new PasswordTransformationMethod());
This approach gave me the hint font I wanted AND gives me the behavior I want with the password dots.
I found this useful tip from Dialogs Guide
Tip: By default, when you set an EditText element to use the "textPassword" input type, the font family is set to monospace, so you should change its font family to "sans-serif" so that both text fields use a matching font style.
For example
android:fontFamily="sans-serif"
This is what I did to fix this problem. For some reason I didn't have to set the transformation method so this may be a better solution:
In my xml:
<EditText
android:id="#+id/password_edit_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
In my Activity:
EditText password = (EditText) findViewById( R.id.password_edit_field );
password.setTypeface( Typeface.DEFAULT );
The setTransformationMethod approach breaks android:imeOption for me, and allows carriage returns to be typed into the password field. Instead I'm doing this:
setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
setTypeface(Typeface.DEFAULT);
And am not setting android:password="true" in XML.
The answer manisha provided does work, but it leaves the password field in a nonstandard state compared to the default. That is, the default fontface then applies also to the password field, including both the dot replacements and the preview characters that appears before being replaced with the dots (as well as when it is a "visible password" field).
To fix this and make it 1) look and act exactly like the default textPassword input type, but also 2) allow the hint text to appear in a default (non-monospace) font, you need to have a TextWatcher on the field that can toggle the fontface properly back and forth between Typeface.DEFAULT and Typeface.MONOSPACE based on whether it is empty or not. I created a helper class that can be used to accomplish that:
import android.graphics.Typeface;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
/**
* This class watches the text input in a password field in order to toggle the field's font so that the hint text
* appears in a normal font and the password appears as monospace.
*
* <p />
* Works around an issue with the Hint typeface.
*
* #author jhansche
* #see <a
* href="http://stackoverflow.com/questions/3406534/password-hint-font-in-android">http://stackoverflow.com/questions/3406534/password-hint-font-in-android</a>
*/
public class PasswordFontfaceWatcher implements TextWatcher {
private static final int TEXT_VARIATION_PASSWORD =
(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
private TextView mView;
/**
* Register a new watcher for this {#code TextView} to alter the fontface based on the field's contents.
*
* <p />
* This is only necessary for a textPassword field that has a non-empty hint text. A view not meeting these
* conditions will incur no side effects.
*
* #param view
*/
public static void register(TextView view) {
final CharSequence hint = view.getHint();
final int inputType = view.getInputType();
final boolean isPassword = ((inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION))
== TEXT_VARIATION_PASSWORD);
if (isPassword && hint != null && !"".equals(hint)) {
PasswordFontfaceWatcher obj = new PasswordFontfaceWatcher(view);
view.addTextChangedListener(obj);
if (view.length() > 0) {
obj.setMonospaceFont();
} else {
obj.setDefaultFont();
}
}
}
public PasswordFontfaceWatcher(TextView view) {
mView = view;
}
public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
// Not needed
}
public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
if (s.length() == 0 && after > 0) {
// Input field went from empty to non-empty
setMonospaceFont();
}
}
public void afterTextChanged(final Editable s) {
if (s.length() == 0) {
// Input field went from non-empty to empty
setDefaultFont();
}
}
public void setDefaultFont() {
mView.setTypeface(Typeface.DEFAULT);
}
public void setMonospaceFont() {
mView.setTypeface(Typeface.MONOSPACE);
}
}
Then to make use of it, all you need to do is call the register(View) static method. Everything else is automatic (including skipping the workaround if the view does not require it!):
final EditText txtPassword = (EditText) view.findViewById(R.id.txt_password);
PasswordFontfaceWatcher.register(txtPassword);
There are many way for solving this problem but each way have pros and cons. Here is my testing
I only face this font problem in some device (list at the end of my answer) when enable input password by
edtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
If I use android:inputType="textPassword", this problem don't happened
Something I have tried
1) Use setTransformationMethod instead inputType
edtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
Font will working well
Keyboard display not very well (it only display text, don't display number on top of text)
2) Use Typeface.DEFAULT
setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
setTypeface(Typeface.DEFAULT);
Keyboard display well,
Font may working not well. Example sans-serif-light is a default font for all View in my application => after setTypeface(Typeface.DEFAULT), the EditText font still look different in some device
3) Use android:fontFamily="sans-serif"
For some device, it will CRASH, check my answer here https://stackoverflow.com/a/52421199/5381331. And also font still look different
MY SOLUTION
cache the typeface before setInputType then reuse it
Typeface cache = edtPassword.getTypeface();
edtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
edtPassword.setTypeface(cache);
Testing
Some device face font problem
Xiaomi A2 (8.0.1)
Pixel XL (8.1.0)
Sony Xperia Z5 Au (SOV32) (6.0)
Arrow NX (F-04G) (6.0.1)
Kyocera (S2) (7.0)
Some device not face font problem
Samsung S4 (SC-04E) (5.0.1)
Samsung Galaxy Node 5 (5.1.1)
Samsung S7 Edge (SM-G935F) (7.0)
The other answers are the right solution for most cases.
However, if you're using a custom EditText subclass to, say, apply a custom font by default, there's a subtle issue. If you set the custom font in the constructor of your subclass, it will still be overwritten by the system if you set inputType="textPassword".
In this case, move your styling to onAttachedToWindow after your super.onAttachedToWindow call.
Example implementation:
package net.petosky.android.ui;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.EditText;
/**
* An EditText that applies a custom font.
*
* #author cory#petosky.net
*/
public class EditTextWithCustomFont extends EditText {
private static Typeface customTypeface;
public EditTextWithCustomFont(Context context) {
super(context);
}
public EditTextWithCustomFont(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EditTextWithCustomFont(
Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* Load and store the custom typeface for this app.
*
* You should have a font file in: project-root/assets/fonts/
*/
private static Typeface getTypeface(Context context) {
if (customTypeface == null) {
customTypeface = Typeface.createFromAsset(
context.getAssets(), "fonts/my_font.ttf");
}
return customTypeface;
}
/**
* Set a custom font for our EditText.
*
* We do this in onAttachedToWindow instead of the constructor to support
* password input types. Internally in TextView, setting the password
* input type overwrites the specified typeface with the system default
* monospace.
*/
#Override protected void onAttachedToWindow() {
super.onAttachedToWindow();
// Our fonts aren't present in developer tools, like live UI
// preview in AndroidStudio.
if (!isInEditMode()) {
setTypeface(getTypeface(getContext()));
}
}
}
I know this may be the older one but I have humped into something related to this issue when I used InputTypeand app:passwordToggleEnabled="true"together.
So, writing this, as it may help someone over here.
I want to use a custom font to password field along with app:passwordToggleEnabled option for my password input field. But in 27.1.1 (while writing this) support library, it was crashing.
So the code was like below,
<android.support.design.widget.TextInputLayout
android:id="#+id/input_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/_10dp"
android:layout_marginTop="#dimen/_32dp"
android:hint="#string/current_password"
android:textColorHint="#color/hint_text_color"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:passwordToggleEnabled="true"
app:passwordToggleTint="#color/black">
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start|left"
android:maxLines="1"
android:textAlignment="viewStart"
android:textColor="#color/black"
android:textColorHint="#color/camel"
android:textSize="#dimen/txt_16sp"
app:font_style="regular"
app:drawableEnd="#drawable/ic_remove_eye" />
</android.support.design.widget.TextInputLayout>
Above code do not have inputType defined in XML
EditText password = (EditText) findViewById(R.id.password);
password.setTransformationMethod(new PasswordTransformationMethod());
And in Java, setTransformationMethod will help me acquire the properties of textPassword input type and also I'm happy my custom font style.
But the below-mentioned crash happened in all API levels with 27.1.1 support library.
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.design.widget.CheckableImageButton.setChecked(boolean)'
on a null object reference
This was crashing due to the onRestoreInstanceState inside TextInputLayout class.
Reproduce Steps: Toggle the password visibility and minimize the app and open from the recent apps. Uh,ho Crashed!
All I needed is default password toggle option (using support library) and custom font in the password input field.
After some time, figured out by doing as below,
<android.support.design.widget.TextInputLayout
android:id="#+id/input_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/_10dp"
android:layout_marginTop="#dimen/_32dp"
android:hint="#string/current_password"
android:textColorHint="#color/hint_text_color"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:passwordToggleEnabled="true"
app:passwordToggleTint="#color/black">
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start|left"
android:maxLines="1"
android:textAlignment="viewStart"
android:textColor="#color/black"
android:textColorHint="#color/camel"
android:textSize="#dimen/txt_16sp"
app:font_style="regular"
app:drawableEnd="#drawable/ic_remove_eye"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
In XML, added android:inputType="textPassword"
TextInputLayout inputPassword = findViewById(R.id.input_password);
EditText password = findViewById(R.id.password);
EditText userName = findViewById(R.id.user_name);
// Get the typeface of user name or other edit text
Typeface typeface = userName.getTypeface();
if (typeface != null)
inputLayout.setTypeface(typeface); // set to password text input layout
In above java code,
I acquired the custom typeface from username EditText and applied it to TextInputLayout of the password field. Now you don't need to set the typeface explicitly to the password EditText as it will acquire the TextInputLayout property.
Also, I removed password.setTransformationMethod(new PasswordTransformationMethod());
By doing this way, passwordToggleEnabled is working, the custom font is also applied and bye-bye to the crash. Hope this issue will be fixed in upcoming support releases.
You can also use a custom Widget. It's very simple and it doesn't clutter your Activity/Fragment code.
Here's the code:
public class PasswordEditText extends EditText {
public PasswordEditText(Context context) {
super(context);
init();
}
public PasswordEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PasswordEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setTypeface(Typeface.DEFAULT);
}
}
And your XML will look like this:
<com.sample.PasswordEditText
android:id="#+id/password_edit_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"
android:password="true" />
use the calligraphy library.
then it still wont update the password fields with the right font. so do this in code not in xml:
Typeface typeface_temp = editText.getTypeface();
editText.setInputType(inputType); /*whatever inputType you want like "TYPE_TEXT_FLAG_NO_SUGGESTIONS"*/
//font is now messed up ..set it back with the below call
editText.setTypeface(typeface_temp);
I recently added the ability to change toggle monospace on/off to a extension of EditText specifically for passwords it may help some people. It doesn't use android:fontFamily so is compatible <16.
You can also use the
<android.support.design.widget.TextInputLayout/>
together with
<android.support.v7.widget.AppCompatEditText/>
I use this solution to toggle the Typeface depending on hint visibility. It's similar to Joe's answer, but extending EditText instead:
public class PasswordEditText extends android.support.v7.widget.AppCompatEditText {
public PasswordEditText(Context context) {
super(context);
}
public PasswordEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PasswordEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
if (text.length() > 0) setTypeface(Typeface.MONOSPACE);
else setTypeface(Typeface.DEFAULT);
}
}
In case you are using the calligraphy library in combination with a TextInputLayout and an EditText, the following code works well.
EditText password = (EditText) findViewById(R.id.password);
TextInputLayout passwordLayout = (TextInputLayout) findViewById(R.id.passwordLayout);
Typeface typeface_temp = password.getTypeface();
password.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
password.setTypeface(typeface_temp);
passwordLayout.setTypeface(typeface_temp);
A weird case perhaps, but I have experimented with this and found out that:
password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
password.setTransformationMethod(new PasswordTransformationMethod());
changed the size of the font of the hint instead of the font itself! This is still an undesired effect. Strangely enough, the reverse operation:
password.setTransformationMethod(new PasswordTransformationMethod());
password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
Keeps the same font size.
I found a sure solution to this problem
Best way to Hello ,I found a sure solution to this problem
The best way is to create a custom editText and save value of typeface as a temp and then apply the method to the InputType changes , Finally, we set back the value of temp type face to the editText. like so :
public class AppCompatPasswordEditText extends AppCompatEditText {
public AppCompatPasswordEditText(Context context) {
super(context);
}
public AppCompatPasswordEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AppCompatPasswordEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
// Our fonts aren't present in developer tools, like live UI
// preview in AndroidStudio.
Typeface cache = getTypeface();
if (!isInEditMode() && cache != null) {
setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
setTypeface(cache);
}
}
}
This how to make input password that has hint which not converted to * and default typeface !!.
On XML :
android:inputType="textPassword"
android:gravity="center"
android:ellipsize="start"
android:hint="Input Password !."
On Activity :
inputPassword.setTypeface(Typeface.DEFAULT);
thanks to : mango and rjrjr for the insight :D.
like the above but make sure the fields do not have the bold style in xml as they will never look the same even with the above fix!