それはエラーテキストがちょうどTextView
ですが、TextAppearance
スタイルは唯一のテキスト自体に影響を与え、ないTextView
は(離れてそれらの属性に配慮しサイジングから)それをレイアウトする方法を本当です。 errorTextAppearance
でエラーテキストのサイズ、書体、色などを設定することはできますが、にはellipsize
またはmaxLines
を設定することはできません。
エラーはちょうどTextView
なので、私たちは自分自身で必要な属性を設定することができます。 TextInputLayout
の子孫のすべてView
を繰り返し処理することができますが、TextInputLayout
はEditText
ではないTextView
を保持できるため、扱いにくく、信頼性が低くなります。私は通常、このようなことの反映を好む。 setErrorEnabled()
メソッドがtrue
で呼び出されたとき
エラーTextView
が作成され、メソッドがfalse
で呼び出された場合、そのフィールドは無効になります。これを外部的に追跡するのではなく、TextInputLayout
をサブクラス化し、エラーが発生するとエラーTextView
に目的の属性を設定する方が簡単です。インスタンス化中にsetErrorEnabled()
が自動的に呼び出されるので、これを有効にするためにメソッドを明示的に呼び出す必要はありません。例えば
:
public class CustomTextInputLayout extends TextInputLayout {
public CustomTextInputLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setErrorEnabled(boolean enabled) {
super.setErrorEnabled(enabled);
if (!enabled) {
return;
}
try {
Field errorViewField = TextInputLayout.class.getDeclaredField("mErrorView");
errorViewField.setAccessible(true);
TextView errorView = (TextView) errorViewField.get(this);
if (errorView != null) {
errorView.setMaxLines(1);
errorView.setEllipsize(TextUtils.TruncateAt.END);
}
}
catch (Exception e) {
// At least log what went wrong
e.printStackTrace();
}
}
}
これはTextInputLayout
のドロップイン置換され、そしてあなただけ通常のクラスと同じように、あなたのレイアウトでそれを使用することができます。完全期すため
<com.mycompany.myapp.CustomTextInputLayout
android:id="@+id/til"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputEditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.mycompany.myapp.CustomTextInputLayout>
、私はTextInputLayout
の最初TextView
子を見つけるために、上記の方法の代わりに使用することができ、次のものがあります必要な属性を設定します。基本的なデフォルトのTextInputLayout
では、エラーTextView
はが最初に見つかったはずです。チェックを追加したい場合は、見つかった子のテキストとTextInputLayout
のエラーとして設定した子を比較することができます。
// Returns true if found
private static boolean findErrorView(ViewGroup vg) {
final int count = vg.getChildCount();
for (int i = 0; i < count; ++i) {
final View child = vg.getChildAt(i);
if(child instanceof ViewGroup) {
if(findErrorView((ViewGroup) child)) {
return true;
}
}
else if (child.getClass().equals(TextView.class)) {
setAttributes((TextView) child);
return true;
}
}
return false;
}
private static void setAttributes(TextView t) {
t.setMaxLines(1);
t.setEllipsize(TextUtils.TruncateAt.END);
}
TextInputLayout
ViewGroup
なので、あなただけのサブクラス内、または外部のいずれか、そのインスタンスに直接findErrorView()
を呼び出すことができます。ただし、エラーTextView
は、エラーが有効になるたびに新たに作成され、無効にされると破棄されます。これらの設定はそれを介して持続されません。
はXMLに追加idでエラーのTextViewを取得することができ、このライン アンドロイド:単一行= "true" を –
@MalikAbuQaoudはすでにそれを試み、それが動作しません。 singleLineは廃止されました – andrei
singleLIneはまだ動作していますが、それは私と一緒に動作します。楕円をマーキーに変更しようとしました –