Android의 비밀번호 힌트 글꼴
EditText가 암호 모드 인 경우 힌트가 다른 글꼴 (커 런서?)로 표시되는 것 같습니다. 어떻게 피할 수 있습니까? EditText가 암호 모드가 아닌 경우와 동일한 글꼴로 힌트를 표시하고 싶습니다.
내 현재 XML :
<EditText
android:hint="@string/edt_password_hint"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"
android:singleLine="true" />
xml에서 서체를 변경해도 힌트 텍스트에서 작동하지 않았습니다. 두 가지 솔루션을 찾았으며 두 번째 솔루션은 더 나은 행동을 취합니다.
1) android:inputType="textPassword"
xml 파일에서 제거 하고 대신 java로 설정하십시오.
EditText password = (EditText) findViewById(R.id.password_text);
password.setTransformationMethod(new PasswordTransformationMethod());
이 방법을 사용하면 힌트 글꼴이 좋아 보이지만 편집 필드에 입력 할 때 각 문자가 일반 문자로 표시되지 않고 암호 점으로 바뀝니다. 또한 전체 화면으로 입력 할 때 점이 나타나지 않지만 암호는 일반 텍스트로 나타납니다.
2) android:inputType="textPassword"
XML을 그대로 두십시오 . Java에서는 또한 서체와 passwordMethod를 설정합니다.
EditText password = (EditText) findViewById(R.id.register_password_text);
password.setTypeface(Typeface.DEFAULT);
password.setTransformationMethod(new PasswordTransformationMethod());
이 접근 방식은 내가 원하는 힌트 글꼴을 제공했으며 암호 점으로 원하는 동작을 제공합니다.
희망이 도움이됩니다!
대화 상자 가이드 에서이 유용한 팁을 찾았습니다.
팁 : 기본적으로 "textPassword"입력 유형을 사용하도록 EditText 요소를 설정하면 글꼴 패밀리가 고정 폭으로 설정되므로 두 텍스트 필드에서 일치하는 글꼴을 사용하도록 글꼴 패밀리를 "sans-serif"로 변경해야합니다. 스타일.
예를 들어
android:fontFamily="sans-serif"
이것이 내가이 문제를 해결하기 위해 한 것입니다. 어떤 이유로 나는 변환 방법을 설정하지 않아도되어 더 나은 해결책이 될 수 있습니다.
내 XML에서 :
<EditText
android:id="@+id/password_edit_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
내 Activity
:
EditText password = (EditText) findViewById( R.id.password_edit_field );
password.setTypeface( Typeface.DEFAULT );
setTransformationMethod 접근 방식은 나를 위해 android : imeOption을 중단하고 캐리지 리턴을 비밀번호 필드에 입력하도록 허용합니다. 대신 나는 이것을하고있다 :
setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
setTypeface(Typeface.DEFAULT);
그리고 XML에서 android : password = "true"를 설정하지 않습니다.
제공된 답변 manisha는 작동하지만 암호 필드를 기본값과 비교하여 비표준 상태로 둡니다. 즉, 기본 글꼴은 도트 대체 및 도트로 교체되기 전에 나타나는 미리보기 문자 ( "표시 가능한 비밀번호"필드 인 경우)를 포함하여 비밀번호 필드에도 적용됩니다.
이 문제를 해결하고 1) 기본 textPassword
입력 유형 과 똑같이 보이고 작동 하지만 2) 힌트 텍스트가 기본 (단일 공백이 아닌) 글꼴로 표시 TextWatcher
되도록하려면 필드에 전환 할 수있는 필드가 있어야합니다. 제대로 앞뒤로 사이 fontface Typeface.DEFAULT
및 Typeface.MONOSPACE
기반 비어 여부에. 나는 그것을 달성하는 데 사용할 수있는 도우미 클래스를 만들었습니다.
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);
}
}
그런 다음이를 사용하려면 register(View)
정적 메소드를 호출하기 만하면됩니다. 다른 모든 것은 자동입니다 (보기가 필요하지 않으면 해결 방법을 건너 뛰는 것을 포함하여)!
final EditText txtPassword = (EditText) view.findViewById(R.id.txt_password);
PasswordFontfaceWatcher.register(txtPassword);
이 문제를 해결하는 방법은 여러 가지가 있지만 각 방법마다 장단점이 있습니다. 여기 내 테스트가 있습니다
입력 암호를 활성화 할 때 일부 장치 (응답 끝에있는 목록) 에서만 이 글꼴 문제에 직면 합니다.
edtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
을 사용 android:inputType="textPassword"
하면이 문제 가 발생 하지 않습니다
내가 시도한 것
1) setTransformationMethod
대신 사용inputType
edtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
- 글꼴이 잘 작동합니다
- 키보드가 잘 표시 되지 않음 (텍스트 만 표시하고 텍스트 위에 숫자를 표시하지 않음)
2) 사용 Typeface.DEFAULT
setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
setTypeface(Typeface.DEFAULT);
- 키보드 디스플레이 ,
- 글꼴 이 제대로 작동하지 않을 수 있습니다 . 예
sans-serif-light
는View
내 응용 프로그램의 모든 기본 글꼴입니다 => aftersetTypeface(Typeface.DEFAULT)
,EditText
글꼴 은 일부 장치에서 여전히 다르게 보입니다.
3) 사용 android:fontFamily="sans-serif"
- 일부 장치의 경우 CRASH 이며 https://stackoverflow.com/a/52421199/5381331에서 내 대답을 확인 하십시오 . 또한 글꼴은 여전히 다르게 보입니다.
내 솔루션
서체를 캐시 한
setInputType
다음 재사용하십시오
Typeface cache = edtPassword.getTypeface();
edtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
edtPassword.setTypeface(cache);
일부 장치 얼굴 글꼴 문제 테스트
- 샤오 미 A2 (8.0.1)
- 픽셀 XL (8.1.0)
- 소니 Xperia Z5 Au (SOV32) (6.0)
- Arrow NX (F-04G) (6.0.1)
- 교세라 (S2) (7.0)
글꼴 문제가 아닌 일부 장치
- 삼성 S4 (SC-04E) (5.0.1)
- 삼성 Galaxy Node 5 (5.1.1)
- 삼성 S7 엣지 (SM-G935F) (7.0)
다른 답변은 대부분의 경우에 적합한 솔루션입니다.
그러나 사용자 정의 EditText
하위 클래스를 사용하여 기본적으로 사용자 정의 글꼴을 적용하는 경우 미묘한 문제가 있습니다. 서브 클래스의 생성자에서 사용자 정의 글꼴을 설정 한 경우을 설정하면 시스템에서 여전히 해당 글꼴을 덮어 씁니다 inputType="textPassword"
.
이 경우 스타일링을 통화 onAttachedToWindow
후로 이동하십시오 super.onAttachedToWindow
.
구현 예 :
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()));
}
}
}
사용자 정의 위젯을 사용할 수도 있습니다. 매우 간단하며 활동 / 조각 코드를 어지럽히 지 않습니다.
코드는 다음과 같습니다.
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);
}
}
XML은 다음과 같습니다.
<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" />
나는이 나이가 하나가 될 수 있습니다 알고 있지만 내가 사용하는 경우이 문제와 관련된 무언가로 숙일 한 InputType
과 app:passwordToggleEnabled="true"
함께.
여기에 누군가 도움이 될 수 있으므로 이것을 작성하십시오.
app:passwordToggleEnabled
비밀번호 입력 필드 옵션 과 함께 사용자 정의 글꼴을 비밀번호 필드에 사용하고 싶습니다 . 그러나 27.1.1 (이 글을 쓰는 동안) 지원 라이브러리에서 충돌이 발생했습니다.
코드는 아래와 같습니다.
<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>
위의 코드는 inputType
XML로 정의 되지 않았습니다
EditText password = (EditText) findViewById(R.id.password);
password.setTransformationMethod(new PasswordTransformationMethod());
그리고 Java에서는 입력 유형 setTransformationMethod
의 속성을 얻는 데 도움이되며 textPassword
사용자 정의 글꼴 스타일이 만족 스럽습니다.
그러나 아래 언급 된 충돌은 27.1.1 지원 라이브러리가있는 모든 API 수준에서 발생했습니다.
java.lang.NullPointerException : null 객체 참조에서 가상 메소드 'void android.support.design.widget.CheckableImageButton.setChecked (boolean)'을 호출하려고 시도했습니다.
onRestoreInstanceState
내부 TextInputLayout
클래스 로 인해 충돌이 발생했습니다 .
재현 단계 : 비밀번호 표시를 토글하고 앱을 최소화하고 최근 앱에서 엽니 다. 어, 호는 추락했다!
비밀번호 입력 필드에 기본 비밀번호 전환 옵션 (지원 라이브러리 사용)과 사용자 지정 글꼴 만 있으면됩니다.
얼마 후, 다음과 같이하여 알아 냈습니다.
<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>
XML에서 추가 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
위의 자바 코드에서
사용자 이름에서 사용자 정의 서체를 가져 EditText
와서 TextInputLayout
비밀번호 필드에 적용했습니다 . 이제 속성 EditText
을 획득하므로 서체를 암호 로 명시 적으로 설정할 필요가 없습니다 TextInputLayout
.
또한 제거했습니다 password.setTransformationMethod(new PasswordTransformationMethod());
이 방법 passwordToggleEnabled
으로 작동하면 사용자 정의 글꼴도 충돌에 적용됩니다. 이 문제가 향후 지원 릴리스에서 해결되기를 바랍니다.
서예 라이브러리를 사용하십시오 .
그런 다음 여전히 올바른 글꼴로 비밀번호 필드를 업데이트하지 않습니다. 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);
최근 에 암호를 위해 EditText 의 확장으로 토글 모노 스페이스를 켜거나 끄는 기능을 추가하여 일부 사람들에게 도움이 될 수 있습니다. 사용하지 않으므로 android:fontFamily
<16과 호환됩니다.
당신은 또한 사용할 수 있습니다
<android.support.design.widget.TextInputLayout/>
함께
<android.support.v7.widget.AppCompatEditText/>
힌트 가시성에 따라이 솔루션을 사용하여 서체를 토글합니다. Joe의 답변과 비슷하지만 EditText를 대신 확장합니다.
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);
}
}
TextInputLayout 및 EditText와 함께 서예 라이브러리 를 사용하는 경우 다음 코드가 효과적입니다.
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);
아마도 이상한 경우이지만, 나는 이것을 실험하고 그것을 발견했습니다.
password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
password.setTransformationMethod(new PasswordTransformationMethod());
글꼴 자체 대신 힌트 글꼴 의 크기를 변경했습니다 ! 이것은 여전히 바람직하지 않은 효과입니다. 이상하게도 역 동작 :
password.setTransformationMethod(new PasswordTransformationMethod());
password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
같은 글꼴 크기를 유지합니다.
이 문제에 대한 확실한 해결책을 찾았습니다.
안녕하세요, 가장 좋은 방법은이 문제에 대한 확실한 해결책을 찾았습니다.
가장 좋은 방법은 사용자 정의 editText를 작성하고 서체의 값을 임시로 저장 한 다음 메소드를 InputType changes에 적용하는 것입니다. 마지막으로 temp 유형의 페이스 값을 editText로 다시 설정합니다. 이렇게 :
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);
}
}
}
이것은 * 및 기본 서체 !!로 변환되지 않은 힌트가있는 입력 암호를 만드는 방법입니다.
XML에서 :
android:inputType="textPassword"
android:gravity="center"
android:ellipsize="start"
android:hint="Input Password !."
활동 중 :
inputPassword.setTypeface(Typeface.DEFAULT);
감사 : mango와 rjrjr에 대한 통찰력 : D.
위와 같이 xml에서 필드가 굵은 스타일로 표시되지 않도록하십시오. 위의 수정으로도 똑같이 보이지 않습니다!
참고 URL : https://stackoverflow.com/questions/3406534/password-hint-font-in-android
'Programing' 카테고리의 다른 글
두 정수를 나눠서 double을 얻는 방법 (0) | 2020.04.06 |
---|---|
Twitter Bootstrap 3에서 버튼을 가운데에 맞추는 방법은 무엇입니까? (0) | 2020.04.05 |
C ++에서 문자열이 다른 문자열로 끝나는 지 확인 (0) | 2020.04.05 |
터미널을 통해 JavaScript 스크립트를 어떻게 실행합니까? (0) | 2020.04.05 |
여러 명령의 Bash 종료 상태를 효율적으로 확인 (0) | 2020.04.05 |