java - CustomEditText 的奇怪行为
问题描述
我创建了一个自定义EditText
以适应我的应用程序的设计。应该有一个提示,当EditText
它被聚焦时,提示应该被着色并向右移动。当它不再聚焦时,提示要么回到左侧,要么,如果将文本写入EditText
,它停留在右侧,只是将颜色更改回默认提示颜色。
这是代码,它工作得非常完美:( LayoutWrapContentUpdater在这里进一步解释)
public class CustomEditText extends ConstraintLayout {
private EditText textField;
private TextView hint;
private float hintSize;
private float hintSizeFocused;
private int hintColorFocused;
private int hintColor;
public CustomEditText(Context context) {
this(context, null);
}
public CustomEditText(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.custom_edit_text, this, true);
setClickable(false);
textField = findViewById(R.id.custom_edit_text_text_field);
textField.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
focusHint();
} else {
unfocusHint();
}
}
});
hint = findViewById(R.id.custom_edit_text_hint);
hint.setClickable(false);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomEditText, defStyleAttr, 0);
hintSize = a.getDimension(R.styleable.CustomEditText_hintSize, dpToPx(DEF_HINT_SIZE));
hint.setTextSize(hintSize);
hintSizeFocused = a.getDimension(R.styleable.CustomEditText_hintSizeFocused, dpToPx(DEF_HINT_SIZE_FOCUSED));
if(a.hasValue(R.styleable.CustomEditText_hint)) {
hint.setText(a.getText(R.styleable.CustomEditText_hint));
}
hintColorFocused = a.getColor(R.styleable.CustomEditText_hintColorFocused, getResources().getColor(R.color.colorPrimary));
hintColor = a.getColor(R.styleable.CustomEditText_hintColor, getResources().getColor(R.color.def_hint_color));
if (a.hasValue(R.styleable.CustomEditText_customBackground)) {
Drawable background = a.getDrawable(R.styleable.CustomEditText_customBackground);
textField.setBackground(background);
}
if(a.getBoolean(R.styleable.CustomEditText_isPassword, false)) {
textField.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
textField.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
textField.setTextSize(a.getDimension(R.styleable.CustomEditText_textSize, dpToPx(DEF_TEXT_SIZE)));
a.recycle();
}
private void focusHint() {
hint.setTextSize(hintSizeFocused);
LayoutWrapContentUpdater.wrapContentAgain(this);
hint.setTextColor(hintColorFocused);
if(textField.getText().toString().isEmpty())
moveHintToRight();
if(textField.getPaddingRight() == 0) {
textField.setPadding(textField.getPaddingLeft(), textField.getPaddingTop(), hint.getWidth() + dpToPx(HINT_MARGIN_SIDE), textField.getPaddingBottom());
}
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(textField, InputMethodManager.SHOW_IMPLICIT);
}
private void unfocusHint() {
hint.setTextColor(hintColor);
if(textField.getText().toString().isEmpty()) {
moveHintToLeft();
hint.setTextSize(hintSize);
LayoutWrapContentUpdater.wrapContentAgain(this);
}
}
private void moveHintToRight() {
int horizontalDistance = textField.getWidth() - hint.getWidth() - dpToPx(HINT_MARGIN_SIDE * 2);
TranslateAnimation anim = new TranslateAnimation(0, horizontalDistance, 0, 0);
anim.setDuration(ANIMATION_DURATION);
anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {
if(textField.hasFocus()) {
ConstraintLayout l = findViewById(R.id.custom_edit_text_constraint_layout);
ConstraintSet set = new ConstraintSet();
set.clone(l);
set.clear(R.id.custom_edit_text_hint, ConstraintSet.LEFT);
set.connect(R.id.custom_edit_text_hint, ConstraintSet.RIGHT, R.id.custom_edit_text_constraint_layout, ConstraintSet.RIGHT, dpToPx(HINT_MARGIN_SIDE));
set.applyTo(l);
}
}
@Override
public void onAnimationRepeat(Animation animation) {}
});
hint.startAnimation(anim);
}
private void moveHintToLeft() {
ConstraintSet set = new ConstraintSet();
ConstraintLayout l = findViewById(R.id.custom_edit_text_constraint_layout);
set.clone(l);
set.clear(R.id.custom_edit_text_hint, ConstraintSet.RIGHT);
set.connect(R.id.custom_edit_text_hint, ConstraintSet.LEFT, R.id.custom_edit_text_constraint_layout, ConstraintSet.LEFT, dpToPx(HINT_MARGIN_SIDE));
set.applyTo(l);
}
}
属性:
<resources>
<declare-styleable name="CustomEditText">
<attr name="hintSize" format="dimension"/>
<attr name="hintSizeFocused" format="dimension"/>
<attr name="hint" format="string"/>
<attr name="hintColorFocused" format="color"/>
<attr name="hintColor" format="color"/>
<attr name="customBackground" format="integer"/>
<attr name="isPassword" format="boolean"/>
<attr name="textSize" format="dimension"/>
</declare-styleable>
</resources>
XML 中的示例:
<com.workoutlog.workoutlog.views.CustomEditText
android:layout_width="match_parent"
android:layout_height="@dimen/textfield_height"
app:hint="@string/hint"
app:hintSize="@dimen/hint_size"
/>
如前所述,这是可行的。但是有一件奇怪的事情。CustomEditText
我在片段中使用这些s。现在,当我在一个布局中包含更多它们时,在最后一个中输入一些文本CustomEditText
,转到另一个片段并再次返回该片段(按下后退按钮或调用supportFragmentManager.popBackStack()
),CustomEditText
该片段中的每个都写了最后一个的CustomEditText
文本我打开了新片段,提示不再正常工作(文本被写在提示上,它们不会向右移动)。当我在另一个中输入一些文本CustomEditText
而在最后一个中没有文本时,这不会发生。我无法解释为什么会发生这种情况。
s 位于扩展为片段的CustomEditText
布局内。仅当CustomEditText
在布局的最后一个文本中键入一些文本时才会发生这种情况。
如果您需要更多代码,我可以编辑它。
编辑
Wirling的回答有效,谢谢!但有一件事仍然不起作用:我无法将提示向右移动。恢复状态后,提示又在左侧,并具有默认的 textSize 和 textColor。我将此代码放入onRestoreInstanceState
:
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
for (int i = 0; i < getChildCount(); i++) {
getChildAt(i).restoreHierarchyState(ss.childrenStates);
}
if(!textField.getText().toString().isEmpty()) {
hint.setTextSize(hintSizeFocused);
LayoutWrapContentUpdater.wrapContentAgain(this);
hint.setTextColor(hintColorFocused);
ConstraintSet set = new ConstraintSet();
set.clone(layout);
set.clear(R.id.custom_edit_text_hint, ConstraintSet.LEFT);
set.connect(R.id.custom_edit_text_hint, ConstraintSet.RIGHT, R.id.custom_edit_text_constraint_layout, ConstraintSet.RIGHT, dpToPx(HINT_MARGIN_SIDE));
set.applyTo(layout);
}
}
颜色和尺寸会发生变化,但我不能把它放在右边。
编辑2:
每次childrenState
传递给方法时,我也会收到警告。例如:
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeSparseArray(childrenStates);
}
在这里,我收到以下警告:
Unchecked assignment: 'android.util.SparseArray' to 'android.util.SparseArray<java.lang.Object>'
解决方案
这是因为重复的视图 ID。看看http://trickyandroid.com/saving-android-view-state-correctly/
并将此代码添加到您的课程中:
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.childrenStates = new SparseArray();
for (int i = 0; i < getChildCount(); i++) {
getChildAt(i).saveHierarchyState(ss.childrenStates);
}
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
for (int i = 0; i < getChildCount(); i++) {
getChildAt(i).restoreHierarchyState(ss.childrenStates);
}
}
@Override
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
dispatchFreezeSelfOnly(container);
}
@Override
protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
dispatchThawSelfOnly(container);
}
static class SavedState extends BaseSavedState {
SparseArray childrenStates;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in, ClassLoader classLoader) {
super(in);
childrenStates = in.readSparseArray(classLoader);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeSparseArray(childrenStates);
}
public static final ClassLoaderCreator<SavedState> CREATOR
= new ClassLoaderCreator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel source, ClassLoader loader) {
return new SavedState(source, loader);
}
@Override
public SavedState createFromParcel(Parcel source) {
return createFromParcel(source, null);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
推荐阅读
- java - Shedlock 只选择某些服务器
- java - Zalenium:在java中访问容器文件
- excel - ExcelDNA C# xll - 使用公式时,如果意外按下 Ctrl+Z,它们会突然消失?
- javascript - IntelliJ IDEA 中的 P5.js?
- fpga - 是否可以在 Artix-7 以外的 FPGA 上实现当前的 Rocket Chip Github respo
- javascript - 在 Google Chrome 中正确打印 PDF
- python - 如何通过递归遍历几个列表
- angular - Angular - 无法在 isAngularDecoratorMetadataExpression 读取未定义的属性“种类”
- google-cloud-platform - GCP 共享 VPC:子网未从宿主项目共享到服务项目
- asp.net - 监听事件的 aspx 页面