How to add EditText in listview and get its value dynamically in all the rows?

前端 未结 3 1041
暖寄归人
暖寄归人 2020-12-31 12:09

I have Checkbox and EditText and a Textview in a listView. It gets value for the text view from a list. Checkbox will be checked dynamically. In the same way EditText also c

3条回答
  •  萌比男神i
    2020-12-31 12:53

    Easy and beautiful solution to handle EditText with listView: (Does not require holder or RecycleView or anything else)

    Brief explaination:

    1) In getView method when you inflate the view, apply the myTextWatcher the editText. Pass this EditText to the myTextWatcher()

    2) Inside getView Method find that EditText and set position as editText.setTag [Each time. not only when the view was inflated.]

    3) Define MyTextWatcher. It should have reference to EditText on which it is applied.

    4) myTextWatcher.onTextChanged() will read the tag set to the editText and do the required work

    Modify your getView() method of Adapter class:

    @Override
    public View getView(int position, View convertView, final ViewGroup parent) {
    
            if(convertView==null){
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.single_row_layout,parent,false);
                EditText et = convertView.findViewById(R.id.idEditText);
                et.addTextChangedListener(new MyTextWatcher(et));
            }
    
        //This is again required to find reference to EditText... so that 'position' can be applied on to it as 'tag' EACH time.    
        EditText editText = (EditText) convertView.findViewById(R.id.idEditText);;
    
        //This tag will be used inside onTextChanged()
        editText.setTag(position);
    
    }
    

    Define your MyTextWatcher class as:

    private class MyTextWatcher implements TextWatcher{
        //int position;
        EditText et;
        public MyTextWatcher(EditText editText){
            this.et = editText;
        }
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(et.getTag()!=null){
                // This is required to ensure EditText is edited by user and not through program
                if(et.hasFocus()){
                     int position = (int)et.getTag();
                     String newText = et.getText()+"";
                     //Implement your actions here........
                     //you can get require things/ views from listView.getChildAt(position).. 
                }
    
            }
    
        }
    
        @Override
        public void afterTextChanged(Editable s) {
    
        }
    }
    

提交回复
热议问题