通常のヒントテキストのサイズは、膨張/初期化中にTextInputLayout
に追加されるときにEditText
のテキストサイズに設定されます。この値は最終的にプライベートヘルパークラスのTextInputLayout
に設定され、それを公開する方法やフィールドは公開されていません。
しかし、TextInputLayout
をサブクラス化してEditText
の追加をインターセプトすることで、テキストサイズを少し変えることができます。 EditText
が追加されると、テキストサイズをキャッシュし、希望のヒントサイズをテキストサイズに設定し、スーパークラスに追加してヒントを初期化し、最後にEditText
のテキストサイズを元の値に戻します。例えば
:
public class CustomTextInputLayout extends TextInputLayout {
private float mainHintTextSize;
private float editTextSize;
public CustomTextInputLayout(Context context) {
this(context, null);
}
public CustomTextInputLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.CustomTextInputLayout);
mainHintTextSize = a.getDimensionPixelSize(
R.styleable.CustomTextInputLayout_mainHintTextSize, 0);
a.recycle();
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
final boolean b = child instanceof EditText && mainHintTextSize > 0;
if (b) {
final EditText e = (EditText) child;
editTextSize = e.getTextSize();
e.setTextSize(TypedValue.COMPLEX_UNIT_PX, mainHintTextSize);
}
super.addView(child, index, params);
if (b) {
getEditText().setTextSize(TypedValue.COMPLEX_UNIT_PX, editTextSize);
}
}
// Units are pixels.
public float getMainHintTextSize() {
return mainHintTextSize;
}
// This optional method allows for dynamic instantiation of this class and
// its EditText, but it cannot be used after the EditText has been added.
// Units are scaled pixels.
public void setMainHintTextSize(float size) {
if (getEditText() != null) {
throw new IllegalStateException(
"Hint text size must be set before EditText is added");
}
mainHintTextSize = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, size, getResources().getDisplayMetrics());
}
}
カスタムmainHintTextSize
属性を使用するには、我々は我々だけres/values/
フォルダに以下のファイルを貼り付ける、またはに追加することによって行うことができます、私たちの<resources>
に次のように必要になります既にそこにあるもの。
attrs.xml
<resources>
<declare-styleable name="CustomTextInputLayout" >
<attr name="mainHintTextSize" format="dimension" />
</declare-styleable>
</resources>
カスタム属性を使用することを気にしない場合は、このファイルをスキップして、上述した第3のコンストラクタでTypedArray
処理を削除することができます。
このカスタムクラスはTextInputLayout
のドロップイン置換であり、そのまま使用できます。たとえば、次のように
<com.mycompany.myapp.CustomTextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
app:hintTextAppearance="@style/TextLabel"
app:mainHintTextSize="12sp">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:text="qwerty123" />
</com.mycompany.myapp.CustomTextInputLayout>
残念ながら、この方法を使用して、ヒントテキストサイズはEditText
が追加された後に変更することはできません。それは反射を必要とするでしょう、そして、私はそのような解決策が必要な場合に利用可能です。
パーフェクト。どうもありがとうございます! – Stanis