ListView中Editext防止数据错乱
2023-03-01 本文已影响0人
银弹星空
package com.adapter;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.hnyeyo.publicsecurity.R;
import butterknife.OnClick;
/**
* 相关人员适配器
*/
public class PeopleAdapter extends BaseListAdapter<Data> {
private View.OnClickListener onClickListener;
private boolean isCanEdit = true;
public PeopleAdapter (Callback callback, View.OnClickListener onClickListener) {
super(callback);
this.onClickListener = onClickListener;
}
public void setCanEdit(boolean canEdit) {
isCanEdit = canEdit;
}
public PeopleAdapter (Callback callback) {
super(callback);
}
@Override
protected void convert(ViewHolder vh, Data item, int position) {
EditText name = vh.getView(R.id.newEvent_et_name);
EditText phone = vh.getView(R.id.newEvent_et_phone);
TextView removeButton = vh.getView(R.id.remove_input_button);
//设置按钮能否点击
if (isCanEdit) {
name.setEnabled(true);
phone.setEnabled(true);
removeButton.setClickable(true);
removeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
removeItem(position);
}
});
} else {
name.setEnabled(false);
phone.setEnabled(false);
removeButton.setClickable(false);
}
//需要先移除 TextWatcher
if (name.getTag() instanceof TextWatcher) {
name.removeTextChangedListener((TextWatcher) name.getTag());
}
if (phone.getTag() instanceof TextWatcher) {
phone.removeTextChangedListener((TextWatcher) phone.getTag());
}
name.setText(item.getName());
phone.setText(item.getPhone());
TextWatcher nameTextWatcher =
new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
getDatas().get(position).setName(s.toString().trim());
}
};
//再添加textWatcher
name.addTextChangedListener(nameTextWatcher);
name.setTag(nameTextWatcher);
TextWatcher phoneTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
getDatas().get(position).setPhone(s.toString().trim());
}
};
phone.addTextChangedListener(phoneTextWatcher);
phone.setTag(phoneTextWatcher);
}
@Override
protected int getLayoutId(int position, WhistlingRelationPersonBean item) {
return R.layout.item_add_people;
}
}