在每个子项中添加带有EditTexts的ListView - Android Studio

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在每个子项中添加带有EditTexts的ListView - Android Studio相关的知识,希望对你有一定的参考价值。

我正在创建一个应用程序,允许用户将数据输入每个子单元格。此外,当用户单击最底部的单元格时,它会向父级添加一个额外的子级。但是,当我添加一个新的孩子时,旧的子细胞中的所有输入数据都会消失。

还有一种保存输入每个单元格的所有数据的最佳方法吗?

控制视图的类:

public class CustomWorkout extends AppCompatActivity {

ExpandableListView expandableListView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_custom_workout);

    expandableListView = (ExpandableListView) findViewById(R.id.expWorkout);
    final List<String> headings = new ArrayList<String>();
    final HashMap<String, List<String>> child = new HashMap<String, List<String>>();

    Spinner spinnerSplit = (Spinner) findViewById(R.id.spinnerSplit);

    ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(CustomWorkout.this, R.layout.spinner_item, getResources().getStringArray(R.array.split));
    myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerSplit.setAdapter(myAdapter);

   final ListViewAdapter listViewAdapter = new ListViewAdapter(this, headings, child);
    expandableListView.setAdapter(listViewAdapter);

    spinnerSplit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            headings.clear();

                for (int i = 0; i < position + 1; i++) {
                    String add = "Day " + Integer.toString(i + 1);
                   List<String> put = new ArrayList<String>();
                   put.add("Add a Workout");
                    headings.add(add);
                    child.put(add, put);
                }
            listViewAdapter.notifyDataSetChanged();
            expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                @Override
                public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                    if (childPosition == listViewAdapter.getChildrenCount(groupPosition) - 1) {
                        String header = "Day " + (groupPosition + 1);
                        child.get(header).add("Add a Workout");
                        listViewAdapter.notifyDataSetChanged();
                        return true;
                    }
                    return false;
                }
            });
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });


}

}

适配器类:

public class ListViewAdapter extends BaseExpandableListAdapter {

private List<String> headerTitle;
private HashMap<String, List<String>> childItems;
private Context context;

ListViewAdapter(Context context, List<String> headerTitle, HashMap<String, List<String>> childItems) {
    this.context = context;
    this.headerTitle = headerTitle;
    this.childItems = childItems;
}


@Override
public int getGroupCount() {
    return headerTitle.size();
}

@Override
public int getChildrenCount(int groupPosition) {
    return childItems.get(headerTitle.get(groupPosition)).size();
}

@Override
public Object getGroup(int groupPosition) {
    return headerTitle.get(groupPosition);
}

@Override
public Object getChild(int groupPosition, int childPosition) {
    return childItems.get(headerTitle.get(groupPosition)).get(childPosition);
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    String title = (String) this.getGroup(groupPosition);

    if (convertView == null) {
        LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        convertView = layoutInflater.inflate(R.layout.list_view_header, null);
    }

    TextView textView = (TextView) convertView.findViewById(R.id.headerParent);
    textView.setTypeface(null, Typeface.BOLD);
    textView.setText(title);

    return convertView;
}

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
    int count = getChildrenCount(groupPosition);

    String title = (String) this.getChild(groupPosition, childPosition);
    LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(context.LAYOUT_INFLATER_SERVICE);


    if (convertView == null) {
        if (!isLastChild) {
            convertView = layoutInflater.inflate(R.layout.add_workout, null);
        } else if (isLastChild) {
            convertView = layoutInflater.inflate(R.layout.list_view_child, null);
            TextView textView = (TextView) convertView.findViewById(R.id.headerChild);
            textView.setText(title);
        }
    } else {
        if (isLastChild) {
            convertView = layoutInflater.inflate(R.layout.list_view_child, null);
            TextView textView = (TextView) convertView.findViewById(R.id.headerChild);
            textView.setText(title);
        } else {
            convertView = layoutInflater.inflate(R.layout.add_workout, null);

        }
    }

    return convertView;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}
答案

在你的adapter上,添加一个interface并将其constructor修改为:

public class ListViewAdapter extends BaseExpandableListAdapter {

   private List<String> headerTitle;
   private HashMap<String, List<String>> childItems;
   private Context context;
   HasMap<String, String> editTextValues;
   private OnEditTextChangeListener onEditTextChangeListener;

   public interface OnEditTextChangeListener {
      void onEditChange(String key, String value);
   }

   ListViewAdapter(Context context, List<String> headerTitle, HashMap<String, List<String>> childItems, HasMap<String, String> editTextValues, OnEditTextChangeListener onEditTextChangeListener) {
       this.context = context;
       this.headerTitle = headerTitle;
       this.childItems = childItems;
   }

   ....code code codes....

   @Override
   public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
    int count = getChildrenCount(groupPosition);

    String title = (String) this.getChild(groupPosition, childPosition);
    LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(context.LAYOUT_INFLATER_SERVICE);


    if (convertView == null) {
        if (!isLastChild) {
            convertView = layoutInflater.inflate(R.layout.add_workout, null);
            EditText editText = convertView.findViewById(R.id.idOfYourEditText);
            for (Map.Entry<String, String> entry : editTextValues.entrySet()) { //loop to set the values that you saved
              Log.d("KING_DEBUG", "Key: " + entry.getKey() + " Value:" + entry.getValue()); //add this so we can log it if we are actually saving the edittext values
              if (entry.getKey().equals(title)) {
                 editText.setText(entry.getValue());
              }
            }
            editText.addTextChangedListener(new TextWatcher() {
               @Override
               public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
               }

               @Override
               public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
               }

               @Override
               public void afterTextChanged(Editable editable) {
                  onEditTextChangeListener.onEditChange(title, editable.toString());
               }
           });


        } else if (isLastChild) {
            convertView = layoutInflater.inflate(R.layout.list_view_child, null);
            TextView textView = (TextView) convertView.findViewById(R.id.headerChild);
            textView.setText(title);
        }
    } else {
        if (isLastChild) {
            convertView = layoutInflater.inflate(R.layout.list_view_child, null);
            TextView textView = (TextView) convertView.findViewById(R.id.headerChild);
            textView.setText(title);
        } else {
            convertView = layoutInflater.inflate(R.layout.add_workout, null);
            EditText editText = convertView.findViewById(R.id.idOfYourEditText);
            for (Map.Entry<String, String> entry : editTextValues.entrySet()) { //loop to set the values that you saved
              Log.d("KING_DEBUG", "Key: " + entry.getKey() + " Value:" + entry.getValue()); //add this so we can log it if we are actually saving the edittext values
              if (entry.getKey().equals(title)) {
                 editText.setText(entry.getValue());
              }
            }
            editText.addTextChangedListener(new TextWatcher() {
               @Override
               public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
               }

               @Override
               public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
               }

               @Override
               public void afterTextChanged(Editable editable) {
                  onEditTextChangeListener.onEditChange(title, editable.toString());
               }
           });
        }
    }

    return convertView;
  }
}

在你的activity

public class CustomWorkout extends AppCompatActivity {

   ExpandableListView expandableListView;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_custom_workout);

    expandableListView = (ExpandableListView) findViewById(R.id.expWorkout);
    final List<String> headings = new ArrayList<String>();
    final HashMap<String, List<String>> child = new HashMap<String, List<String>>();
    final HashMap<String, String> editTextValues = new HashMap<String, String>(); //add this

    Spinner spinnerSplit = (Spinner) findViewById(R.id.spinnerSplit);

    ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(CustomWorkout.this, R.layout.spinner_item, getResources().getStringArray(R.array.split));
    myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerSplit.setAdapter(myAdapter);

    final ListViewAdapter listViewAdapter = new ListViewAdapter(this, headings, child, editTextValues, 
       new OnEditTextChangeListener () {
          @Override
          public void onEditChange(String key, String value) {
             editTextValues.put(key, value);
          }
       }); //modified constructor
    expandableListView.setAdapter(listViewAdapter);

    spinnerSplit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            headings.clear();

                for (int i = 0; i < position + 1; i++) {
                    String add = "Day " + Integer.toString(i + 1);
                   List<String> put = new ArrayList<String>();
                   put.add("Add a Workout");
                    headings.add(add);
                    child.put(add, put);
                }
            listViewAdapter.notifyDataSetChanged();
            expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                @Override
                public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                    if (childPosition == listViewAdapter.getChildrenCount(groupPosition) - 1) {
                        String header = "Day " + (groupPosition + 1);
                        child.get(header).add("Add a Workout");
                        listViewAdapter.notifyDataSetChanged();
                        return true;
                    }
                    return false;
                }
            });
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
  }
}

在这里,我们添加了editTextValues,它可以在更换时保存每个editText的值,并且custom listener可以在activity上处理它。

诀窍是保存您输入的内容并在每次显示时进行设置。

以上是关于在每个子项中添加带有EditTexts的ListView - Android Studio的主要内容,如果未能解决你的问题,请参考以下文章

带有茧栏杆的嵌套表单在编辑时会重复子项目

ListView 从第 5 行开始重复 EditTexts 中的相同项目

Android - 通过 ID 从动态 EditTexts 获取数据

Swiftui 将 VStack 子项高度调整为内容高度

在 Android 中添加 ListView 子项文本

带有列表子项可聚焦android的列表视图上下文菜单