programing

Android의 암호 힌트 글꼴

iphone6s 2023. 9. 14. 21:51
반응형

Android의 암호 힌트 글꼴

EditText가 암호 모드일 때 힌트가 다른 글꼴(corrier?)로 표시되는 것 같습니다.어떻게 하면 이걸 피할 수 있을까요?저는 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"javaxml 파일로 합니다.

    텍스트 암호 편집 = (텍스트 편집) ViewById(R.id .password_text) 찾기; password.setTransformationMethod(새 암호 변환Method());

이 방법을 사용하면 힌트 글꼴이 좋아 보이지만 해당 편집 필드에 입력할 때 암호 점으로 바뀌기 전에 일반 텍스트의 각 문자를 볼 수 없습니다.또한 전체 화면에서 입력할 때 점이 나타나지 않고 암호가 투명 텍스트로 나타납니다.

  1. 남기기 android:inputType="textPassword"xml 파일에 합니다.Java에서는 서체와 비밀번호도 설정합니다Method:

    텍스트 암호 편집 = (텍스트 편집) ViewById(R.id .register_password_text); password.setTypeface(Typeface)를 찾습니다.DEFAULT); password.setTransformationMethod(새 암호 변환Method());

이 접근법은 내가 원하는 힌트 폰트와 비밀번호 점으로 내가 원하는 동작을 알려줍니다.

대화 가이드에서 유용한 팁을 찾았습니다.

팁: 기본적으로 텍스트 편집 요소에서 "textPassword" 입력 유형을 사용하도록 설정할 때 글꼴 패밀리는 단일 공간으로 설정되므로, 두 텍스트 필드가 일치하는 글꼴 스타일을 사용하도록 글꼴 패밀리를 "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"를 설정하지 않습니다.

매니샤가 제공한 답변은 효과가 있지만 기본값과 비교하여 암호 필드는 비표준 상태로 유지됩니다.그러면 기본 글꼴은 점 바꾸기와 점으로 바꾸기 전에 나타나는 미리보기 문자("보이는 암호" 필드일 때도 마찬가지)를 포함하여 암호 필드에도 적용됩니다.

을 을 하는 와 하는 와 을 textPassword 유형, 또한공간이 합니다.력형한나트본공가다로록이닌)a(o록et)이닌ed력본,2e한)w,o형totn2 .TextWatcher를 적절히 로 할 수 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나의 어플리케이션 => 에setTypeface(Typeface.DEFAULT) , , , , , , , , , , , , , , , , , , .EditText일부 장치에서 글꼴이 여전히 다르게 보입니다.

3) 사용 android:fontFamily="sans-serif"

  • 어떤 기기의 경우 크래시가 발생합니다. 여기 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);


면 문제부면꼴제치제꼴부e면치e

  • 샤오미 A2 (8.0.1)
  • 픽셀 XL (8.1.0)
  • 소니 엑스페리아 Z5 Au (SOV32) (6.0)
  • 화살표 NX (F-04G) (6.0.1)
  • 교세라(S2)(7.0)

일부 장치가 글꼴 문제에 직면하지 않음

  • 삼성 S4 (SC-04E) (5.0.1)
  • 삼성 갤럭시 노드 5 (5.1.1)
  • 삼성 S7엣지 (SM-G935F) (7.0)

다른 대답은 대부분의 경우에 올바른 해결책입니다.

지정 하는 를 하는 를 EditText서브클래스에서 기본적으로 사용자 지정 글꼴을 적용합니다. 미묘한 문제가 있습니다. 지정 의자정을도서다서u서fefymertlnt의teesrm을fb,uinputType="textPassword".

이 경우 스타일을 다음으로 이동합니다.onAttachedToWindowsuper.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()));
        }
    }
}

이것이 오래된 것일 수도 있다는 것을 알고 있지만 사용할 때 이 문제와 관련된 무언가를 발견했습니다.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>

에는 가 가 .inputTypeXMLXML에

EditText password = (EditText) findViewById(R.id.password);
password.setTransformationMethod(new PasswordTransformationMethod());

setTransformationMethod데이될다다fre될elpe이가을데se의textPassword입력 유형과 맞춤 글꼴 스타일에 만족합니다.

그러나 27.1.1 지원 라이브러리를 사용하는 모든 API 레벨에서 아래와 같은 충돌이 발생했습니다.

java.javaNull 포인터예외:가상 메서드 'void Android'를(를) 호출하려고 시도합니다.지지.설계.위젯.확인 가능한 이미지 버튼.null 개체 참조에서 'Checked(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>

추가 됨 에서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비밀번호 필드를 선택합니다.을로할가다로다e제w할eout'dtednto을로으로EditText그것은 그것을 획득할 것이므로.TextInputLayout소유물.

그리고 제거를 했습니다.password.setTransformationMethod(new PasswordTransformationMethod());

으로써.passwordToggleEnabled작동 중이며, 사용자 지정 글꼴도 적용되며 충돌에 대한 바이바이입니다.이 문제가 향후 지원 릴리스에서 해결되기를 바랍니다.

사용자 지정 위젯을 사용할 수도 있습니다.매우 간단하며 활동/조각 코드를 복잡하게 만들지 않습니다.

코드는 다음과 같습니다.

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" />

캘리그라피 라이브러리를 이용합니다.

그러면 여전히 올바른 글꼴로 암호 필드를 업데이트하지 않습니다. 따라서 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를 만들고 type face의 값을 임시로 저장한 다음 inputType 변경사항에 메소드를 적용하는 것입니다. 마지막으로 temp type face의 값을 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);

감사합니다 : 망고와 rjrjr을 통찰력을 위해 :D.

위와 같이 하지만 필드가 xml의 굵은 스타일을 가지고 있지 않은지 확인하십시오. 위의 수정을 사용해도 결코 동일하게 보이지 않기 때문입니다!

언급URL : https://stackoverflow.com/questions/3406534/password-hint-font-in-android

반응형