[英]Trying to update my custom list adapter of listView using notifyDataSetChanged but not working
添加新文件时如何正确更新 listView 适配器? listView 由数组提供。 我读了很多书并尝试了几件事,但没有任何效果。 我错过了什么吗? notifyDataSetChanged 由于某种原因无法正常工作。
活动.java
创建时:
ListView list2;
CustomList listAdapter;
String[] ficheros;
final File carpeta = new File("/storage/emulated/0/Android/data/cc.openframeworks.androidMultiOFActivitiesExample/files/xml");
list2=(ListView)findViewById(R.id.listview);
list2.setVisibility(GONE);
list2.setCacheColorHint(Color.TRANSPARENT);
ficheros = list.toArray(new String[list.size()]);
List<String> list = new ArrayList<String>();
listAdapter = new CustomList(OFActivityA.this, ficheros,fecha);
list2.setAdapter(listAdapter);
listarFicherosPorCarpeta(carpeta);
@Override
protected void onResume() {
super.onResume();
public void listarFicherosPorCarpeta(final File carpeta) {
for (final File ficheroEntrada: carpeta.listFiles()) {
if (ficheroEntrada.isDirectory()) {
listarFicherosPorCarpeta(ficheroEntrada);
} else {
System.out.println(ficheroEntrada.getName());
list.add(ficheroEntrada.getName());
}
}
listAdapter.notifyDataSetChanged();
}
CustomList.java
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] ficheros;
private final String[] fecha;
public CustomList(Activity context, String[] ficheros, String[] fecha) {
super(context, R.layout.rowlayout, ficheros);
this.context = context;
this.ficheros = ficheros;
this.fecha = fecha;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.rowlayout, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.listtext);
TextView txtFecha = (TextView) rowView.findViewById(R.id.fechatxt);
txtTitle.setTextColor(Color.parseColor("#015D99"));
txtTitle.setHeight(123);
txtFecha.setText(fecha[position]);
txtTitle.setText(ficheros[position]);
return rowView;
}
如果数据集中的内容发生了变化, notifyDataSetChanged()
将起作用。 您在onResume()
中调用它可能会在 function 中的循环完成之前被调用。 尝试更改您的 function 调用并在 for 循环完成后添加notifyDataSetChanged()
。
public void listarFicherosPorCarpeta(final File carpeta) {
for (final File ficheroEntrada: carpeta.listFiles()) {
if (ficheroEntrada.isDirectory()) {
listarFicherosPorCarpeta(ficheroEntrada);
} else {
System.out.println(ficheroEntrada.getName());
list.add(ficheroEntrada.getName());
}
}
listAdapter.notifyDataSetChanged(); //call it here after you have updated your data.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.