java如何将ListAdapter中创建的视图添加到数组
假设我有一个如下所示的适配器:
public class CalculateListingsLVAdapter extends ArrayAdapter {
private String[] Vars;
private String[] VarDescriptions;
private Activity context;
public CalculateListingsLVAdapter(Activity context, String[] Vars, String[] Vardescs) {
super(context, R.layout.make_calculation_lv, Vars);
this.context = context;
this.Vars = Vars;
this.VarDescriptions= Vardescs;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
LayoutInflater inflater = context.getLayoutInflater();
if(convertView==null)
row = inflater.inflate(R.layout.make_calculation_lv, null, true);
TextView titleTV = (TextView) row.findViewById(R.id.VarTitle);
EditText userINP = row.findViewById(R.id.VarInput);
if (!VarDescriptions[position].equals("")) {
String g = Vars[position] + " - " + VarDescriptions[position];
titleTV.setText(g);
} else {
titleTV.setText(Vars[position]);
}
userINP.setTag(Vars[position]);
return row;
}
}
我希望能够从编辑文本中获取输入。很明显,像这样的事情是行不通的:
ListView calcLV = findViewById(R.id.VariablesLV);
EditText et;
View r;
String curform = formula;
for (int i = 0; i < calcLV.getCount(); i++) {
r = calcLV.getChildAt(i);
et = r.findViewById(R.id.VarInput);
String l = (String) et.getTag();
System.out.println(l);
String val = et.getText().toString();
curform = curform.replace(l,val);
}
因为ListView不会始终显示所有项目
因此,我尝试将以下代码添加到适配器:
public ArrayList<EditText> editTxts = new ArrayList<>();
然后将每个userINP editText附加到ArrayList中,以便以后访问。不幸的是,这导致了null对象引用错误,该错误表明我无法将userINP添加到数组中
如何最好地解决这个问题
# 1 楼答案
我刚想出来:
在ArrayAdapter类中,创建一个ArrayList以在编辑编辑文本时存储editText值,如下所示:
然后,在MainActivity中,可以从ArrayList中进行绘制,并使用正则表达式获取变量和值