我正在使用Manishkpr教程创建一个应用程序,您可以在1)layoutone:这里创建一个文件,2)layouttow:显示某个文件夹中所有创建文件的列表视图。
问题:如果创建一个文件,它不会立即显示在ListView中。我发现我应该在layoutone.java中使用以下代码:
LayoutTwo fragment = (LayoutTwo) getFragmentManager().findFragmentByTag("TESTTWO");
fragment.getAdapter().notifyDataSetChanged();
在layoututto.java中,我添加了:
private static final String TAG = "TESTTWO";
//and the function getAdapter:
public CustomArrayAdapter getAdapter() {
return adapter;
}
但是,我在
fragment.getAdapter().notifyDataSetChanged();
上收到一个空指针异常。我怎样才能解决这个问题,这是最好的方法吗?编辑
myList = new ArrayList<RecordedFile>();
File directory = Environment.getExternalStorageDirectory();
file = new File(directory + "/test/");
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
if (checkExtension(list[i].getName()) == true) {
RecordedFile q = new RecordedFile();
q.setTitle(list[i].getName());
q.setFileSize(readableFileSize(list[i].length()));
myList.add(q);
}
}
adapter = new CustomArrayAdapter(myContext,
R.layout.listview_item_row, myList);
listView.setAdapter(adapter);
最佳答案
我正在使用manishkpr上的教程创建一个应用程序,您可以在其中滑动
在1)layoutone:这里创建一个文件和2)layoututwo:显示
特定文件夹中所有已创建文件的列表视图。
问题:如果创建一个文件,它不会立即显示在
ListVIEW。
如果你有两个布局来刷卡,这意味着它们都有自己的观点,可以访问。然后,您可以将ID分配给ListView
,当是刷新数据的时候,只需在ListView
中查找Activity
,获取它的适配器并更新它,如下所示:
ListView list = (ListView) getActivity().findViewById(R.id.theIdOfTheList);
((BaseAdapter)list.getAdapter()).notifyDataSetChanged();
无论你在适配器上调用
notifyDataSetChanged()
,ListVIEW都不会更新,因为它没有看到新文件,从它的角度来看,数据集是完整的。取决于适配器的外观,您有两种选择:重新构建
ListView
的数据,基本上重做当第一次构造ListView
时所做的工作:检查目录并重新列出所有文件。// create the new file
File directory = Environment.getExternalStorageDirectory();
file = new File(directory + "/test/");
File list[] = file.listFiles();
ListView list = (ListView) getActivity().findViewById(R.id.theIdOfTheList);
// I'm assuming your adapter extends ArrayAdapter(?!?)
CustomArrayAdapter caa = (CustomArrayAdapter) list.getAdapter();
caa.clear();
for (int i = 0; i < list.length; i++) {
if (checkExtension(list[i].getName())) {
RecordedFile q = new RecordedFile();
q.setTitle(list[i].getName());
q.setFileSize(readableFileSize(list[i].length()));
caa.add(q);
}
}
或者,您可以手动为新创建的文件创建
RecordFile
对象,并将其添加到现有适配器:ListView list = (ListView) getActivity().findViewById(R.id.theIdOfTheList);
(CustomArrayAdapter) caa = (CustomArrayAdapter) list.getAdapter();
File newFile = new File("directory" + "/test/theNewFileName.extension");
RecordFile rf = new RecordFile();
rf.setTitle(newFile.getName());
rf.setFileSize(readableFileSize(newFile.length()));
// have a method to return a reference of the data list(or a method
// to add the data directly in the adapter)
List<RecordFile> data = caa.getListData();
data.add(rf);
caa.notifyDataSetChanged();
我不知道你的适配器看起来如何,所以试试我说的,如果它不起作用,请为适配器发布代码。