RecyclerView의 완벽한 중첩 EditText

RecyclerView에서 item에 EditText를 끼워 넣으면 항상 초점이 흐트러지고 데이터가 흐트러집니다
주요 원인은 EditText의 초점이 바뀔 때 감청도 변화하고 데이터가 끊임없이 변화하기 때문이다
해결 방법: 초점 변화를 감청하고 초점이 있으면 추가:addTextChangedListener;초점 없이 제거:removeTextChangedListener
키 코드:
mEtCleanGoodsDiscount.setOnFocusChangeListener((v, hasFocus) -> {
    if (hasFocus) {
        //   ,     addTextChangedListener
        addTextWatch(mEtCleanGoodsDiscount, 100.0f);
    } else {
        //   ,     removeTextChangedListener
        removeTextWatch(mEtCleanGoodsDiscount);
    }
});

다음은 프로젝트 중의 사례: 목록에서 상품 가격을 수정하고 할인과 가격의 연동 변화(할인을 수정하고 동시에 가격을 계산한다. 반대로, 동일하다)
1. 다음은 View 사용자 정의
/**
 * @filename ItemPriceView
 * @author:sen
 * @date 2020-01-04  18:22
 * @function:     EditView     
 */
public class ItemPriceView extends FrameLayout {

    private EditText mEtCleanGoodsDiscount;
    private EditText mEtCleanGoodsPrice;
    private PriceTextWatcher mPriceTextWatcher;

    public ItemPriceView(@NonNull Context context) {
        super(context);
        init();
    }

    public ItemPriceView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, 0);
        init();
    }

    public ItemPriceView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_clean_goods_price_view, this, true);
        //   
        mEtCleanGoodsDiscount = view.findViewById(R.id.et_clean_goods_discount);
        //    
        mEtCleanGoodsPrice = view.findViewById(R.id.et_clean_goods_price);

    }

    private WxGoods mWxGoods;

    public void setData(WxGoods wxGoods) {
        this.mWxGoods = wxGoods;


        mEtCleanGoodsDiscount.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                //   ,    ,     100
                addTextWatch(mEtCleanGoodsDiscount, 100.0f);
            } else {
                //   ,    
                removeTextWatch(mEtCleanGoodsDiscount);
            }
        });

        mEtCleanGoodsPrice.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                //   ,    ,     
                addTextWatch(mEtCleanGoodsPrice, wxGoods.price);
            } else {
                //   ,    
                removeTextWatch(mEtCleanGoodsPrice);
            }
        });


        mEtCleanGoodsDiscount.setText(String.format("%.2f", mWxGoods.getCleanDiscount()));
        mEtCleanGoodsPrice.setText(String.format("%.2f", wxGoods.getCleanPrice()));

    }

    private void addTextWatch(EditText editText, double max) {
        InputFilter inputFilter = (source, start, end, dest, dstart, dend) -> {
            //        ,    
            if (TextUtils.isEmpty(source)) {
                return null;
            }
            String dValue = dest.toString();
            String[] splitArray = dValue.split("\\.");
            if (splitArray.length > 1) {
                String dotValue = splitArray[1];
                // 2           
                int diff = dotValue.length() + 1 - 2;
                if (diff > 0) {
                    return source.subSequence(start, end - diff);
                }
            }
            return null;
        };

        editText.setFilters(new InputFilter[]{inputFilter});
        mPriceTextWatcher = new PriceTextWatcher(editText, max);
        editText.addTextChangedListener(mPriceTextWatcher);
    }

    private void removeTextWatch(EditText editText) {
        editText.removeTextChangedListener(mPriceTextWatcher);
    }

    private class PriceTextWatcher extends SimpleTextWatcher {

        private EditText editText;
        private double max = 100.0;

        public PriceTextWatcher(EditText editText, double max) {
            this.editText = editText;
            this.max = max;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String str = s.toString();
            if (str.startsWith(".")) {
                editText.setText("");
                return;
            }
            if (str.startsWith("00")) {
                editText.setText("0");
                editText.setSelection("0".length());
                return;
            }
            if (StringUtils.countMatches(str, ".") > 1 && str.endsWith(".")) {
                String content = str.substring(0, str.length() - 1);
                editText.setText(content);
                editText.setSelection(content.length());
                return;
            }

            if (NumberUtils.toDouble(str) > max) {
                String content = String.valueOf(max);
                editText.setText(content);
                editText.setSelection(content.length());
                return;
            }

            doResult(NumberUtils.toDouble(str), editText.getId() == R.id.et_clean_goods_discount);
        }

    }

    private void doResult(double data, boolean isDiscount) {
        if (isDiscount) {
            //     ,       
            LogUtils.d("     ,       >>>>>" + data);
            mWxGoods.clean_discount = data;
            if (data == 0) {
                mEtCleanGoodsPrice.setText(String.format("%.2f", 0.0f));
                mWxGoods.clean_price = 0.0;
                return;
            }
            mWxGoods.clean_price = mWxGoods.price * data / 100.0f;
            mEtCleanGoodsPrice.setText(String.format("%.2f", mWxGoods.getCleanPrice()));
        } else {
            //      ,      
            LogUtils.d("      ,      >>>>>" + data);
            mWxGoods.clean_price = data;
            if (data == 0) {
                mEtCleanGoodsDiscount.setText(String.format("%.2f", 0.0f));
                mWxGoods.clean_discount = 0.0;
                return;
            }
            mWxGoods.clean_discount = data / mWxGoods.price * 100.0f;
            mEtCleanGoodsDiscount.setText(String.format("%.2f", mWxGoods.getCleanDiscount()));
        }
    }
}

2、item_clean_goods_price_view.xml 레이아웃 파일



    

    

    

    

    

    

좋은 웹페이지 즐겨찾기