我需要为ListView
中的每一行存储隐藏的ID值。基本上是一个变量,包含代码所需的字符串值以及用户不需要查看的内容。
EditText
Button
ViewHolder
注意:请注意,每行都有String
值存储。每行都有一个String
值存储在ViewHolder
中。这就是我想要实现的目标。
我的方法是在String
类中声明一个ViewHolder
变量,希望它将保留该特定行的值。但是我注意到,当适配器回收该行时,字符串值将重置为空字符串。
适配器:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_row, null);
holder = new ViewHolder();
holder.saveName = (Button) convertView.findViewById(R.id.saveName);
holder.nameField = (EditText) convertView.findViewById(R.id.nameField);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
//Button That saves what the user entered in the nameField to the String variable
holder.saveName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
holder.hidden_value = nameField.getText().toString();
}
});
//Just to check whether the value is saved when I recycle listview when scrolling
Log.d("test", holder.hidden_value);
//It logs an empty string. The value from the editext was not saved!
}
static class ViewHolder {
EditText nameField;
Button saveName;
String hidden_value = "";
}
为什么值不会保存在字符串中?当我尝试记录它时,它会记录一个空字符串!我做错了什么?
答案 0 :(得分:2)
您无法在ViewHolder
中存储价值。您使用holder = (ViewHolder) convertView.getTag();
获取ViewHolder
。此ViewHolder
是其他视图的表单标记,而不是您在此位置存储的ViewHolder
。
private SparseArray<String> values = new SparseArray<>();
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_row, null);
holder = new ViewHolder();
holder.saveName = (Button) convertView.findViewById(R.id.saveName);
holder.nameField = (EditText) convertView.findViewById(R.id.nameField);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
//Button That saves what the user entered in the nameField to the String variable
holder.saveName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
values.put(position,nameField.getText().toString());
}
});
//Just to check whether the value is saved when I recycle listview when scrolling
Log.d("test", values.get(position,"null"));
//It logs an empty string. The value from the editext was not saved!
}
static class ViewHolder {
EditText nameField;
Button saveName;
String hidden_value = "";
}
答案 1 :(得分:2)
问题是,ViewHolder
应该包含“视图”而不是“数据”。您需要在此处更改您的实施。将值存储在要传递给适配器的数组中。这是实际保存“数据”的数组。
因此,您的自定义适配器的构造函数将是,
public CategoryListViewAdapter(Context c, ArrayList<MyData> al) {
mContext = c;
mArrayList = al;
....
}
MyData
将有您的ID字段
class Mydata{
String ID;
....
}
有关此主题的完整教程,请参阅this。它有你需要知道的一切。