编辑3我提交了一个新的问题,因为我已经意识到这里原来的问题实际上不是问题。
所以,我有一个片段,从我的应用程序的内部存储获取文件,然后在ListView中列出它们。我用一个数组列表来存放文件名,用一个适配器来填充ListView。如果我调试,我看到所有的项目都在Array List中,就像它们应该的那样,但是由于某种原因,它们没有显示在列表视图中。我完全不知道发生了什么,因为我用完全相同的代码做了一个新的测试应用程序,它工作得很好。
ListerFrag.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_templates, container, false);
ListView listView = (ListView) view.findViewById(R.id.templateFilesList);
ArrayList<String> templateList = new ArrayList<String>();
File myDir = getActivity().getApplicationContext().getFilesDir();
File[] templateFiles = myDir.listFiles();
if(templateFiles != null){
for(File file : templateFiles){
templateList.add(file.getName());
}
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1,
templateList);
listView.setAdapter(arrayAdapter);
return view;
}
XML: <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="-"
android:orientation="vertical"
android:gravity="center_horizontal"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/my_templates"
android:textSize="34sp"
android:gravity="center_horizontal"
android:padding="5dp"
android:layout_marginBottom="10dp"
/>
// relevant ListView
<ListView
android:id="@+id/templateFilesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</ListView>
我一直很困惑。
Edit:我想强调的是,文件"instant-run"正在被显示。默认情况下,该文件位于默认的内部存储目录中。它是数组列表中的第一项。我觉得奇怪的是,第一个文件被识别和显示,但其余的没有。即使它们在数组列表中(通过logcat验证)。
编辑2:更奇怪的。如果我显式地告诉代码显示,比如说,listtitem[1],它会完美地工作。所以我可能正在关注for循环的一个问题。
我对你最后两行有点怀疑。试一试:
ArrayList<String> list = new ArrayList<>();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);