gpt4 book ai didi

java - 尝试使用notifyDataSetChanged更新listView的自定义列表适配器但不起作用

转载 作者:行者123 更新时间:2023-12-02 09:29:39 25 4
gpt4 key购买 nike

添加新文件时如何正确更新我的 listView 适配器? listView 由一个数组提供。我读了很多书,尝试了很多东西,但没有任何效果。我错过了什么吗?由于某种原因,notifyDataSetChanged 无法正常工作。

activity.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();
}

自定义列表.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() 中调用它,它可能会在函数循环完成之前被调用。尝试更改函数调用并在 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.
}

关于java - 尝试使用notifyDataSetChanged更新listView的自定义列表适配器但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58090614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com