我在textinputlayout中有一个编辑文本。我正在尝试将强制字段符号(红色星号)设置为edittext。我已将提示设置为编辑文本。我的代码如下。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" * "
android:layout_gravity="center_vertical"
android:textColor="#ff0000"
android:textSize="15sp" />
<android.support.design.widget.TextInputLayout
android:id="@+id/tilEngNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<EditText
android:id="@+id/engineno"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:layout_marginRight="16dp"
android:hint="Engine No" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
这给了我textinputlayout之外的星号符号。因此,当我开始输入编辑文本时,提示会浮动,但不是星号符号。 我的要求是使星号符号的行为与edittext的提示相同。什么是最好的方法? 任何帮助表示赞赏。提前致谢
答案 0 :(得分:2)
假设您有强制值的EditTexts。您希望提示为红色星号,后面是浅灰色文本。
在EditTexts之后你有了解释:TextView带有红色星号,后跟文字“= field is required”
就我而言,我使用了这个:
showEditTextsAsMandatory ( joinEmailET, joinNameET, passwordET, confirmPasswordET );
showTextViewsAsMandatory ( ( TextView ) findViewById ( R.id.requiredText ) );
public void showEditTextsAsMandatory ( EditText... ets )
{
for ( EditText et : ets )
{
String hint = et.getHint ().toString ();
et.setHint ( Html.fromHtml ( "<font color=\"#ff0000\">" + "* " + "</font>" + hint ) );
}
}
public void showTextViewsAsMandatory ( TextView... tvs )
{
for ( TextView tv : tvs )
{
String text = tv.getText ().toString ();
tv.setText ( Html.fromHtml ( "<font color=\"#ff0000\">" + "* " + "</font>" + text ) );
}
}
答案 1 :(得分:0)
您可以使用一个小技巧来完成此操作,即在Java代码中调用layout_gravity
时必须更改OnFocusChangeListener
。例如:
//Set OnFocusChangeListener for EditText
edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
//astriskText is Object of your textview contains * as text
if (hasFocus) {
//if edittext has focus then move it to top
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) astriskText.getLayoutParams();
lp.gravity= Gravity.TOP;
astriskText.setLayoutParams(lp);
} else if(edittext.getText().toString().length()==0){
//else check if edittext is empty then move it back to center
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) astriskText.getLayoutParams();
lp.gravity= Gravity.CENTER_VERTICAL;
astriskText.setLayoutParams(lp);
}
}
});
答案 2 :(得分:0)
尝试使用html中包含的跨区后缀加入TextInputLayout提示:
public void setRequired(boolean required) {
componentField.setHint(
TextUtils.concat(
componentField.getHint(),
Html.fromHtml(
getContext().getString(
R.string.required_asterisk))));
}
Asterisk代码应该存储在android strings.xml中以便正确转义:
<string name = "required_asterisk"><![CDATA[<font color=\'#cc0029\'> *</font>]]></string>