Edit3:我自己的项目列表布局:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
/>
Edit2:老实说,我可能只是制作一个 for 循环来为每个文件创建按钮。这太让人头疼了,不值得花时间。
编辑:我想强调一个事实,我已经将我的确切代码复制并粘贴到一个新的测试应用程序中并且它运行良好。这可能会给你们一些线索。
经过大量调试,我缩小了一个问题的范围。我正在尝试将项目(文件)添加到 ArrayList,然后将其放入 ArrayAdapter,最后在 ListView 中显示项目。问题是只显示第一个添加的项目。
我是这样尝试的:
ListView listView = (ListView) view.findViewById(R.id.templateFilesList);
ArrayList<String> templateList = new ArrayList<>();
File myDir = getContext().getFilesDir();
File[] templateFiles = myDir.listFiles();
int length = templateFiles.length;
for(int i = 0; i < length; i++){
templateList.add(templateFiles[i].getName());
}
ArrayAdapter arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1,
templateList);
listView.setAdapter(arrayAdapter);
templateFiles[] 数组正确获取了Internal Storage 中的8 个文件(通过logcat/debugger 确认),但ListView 中仅显示第一项。下面是对这个问题的更清楚的了解:
// If I replace the for loop with this:
templateList.add(templateFiles[1].getName());
templateList.add(templateFiles[0].getName());
仅显示 templateFiles[1]。同样,如果我这样做:
templateList.add(templateFiles[0].getName());
templateList.add(templateFiles[1].getName());
仅显示 templateFiles[0]。对出了什么问题有什么想法吗?
这是我的 XML:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.template_housing.MyTemplatesFrag"
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:textColor="@color/black"
android:background="@color/Gold1"
android:gravity="center_horizontal"
android:padding="5dp"
android:layout_marginBottom="10dp"
/>
<ListView
android:id="@+id/templateFilesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</ListView>
最佳答案
如果您要更新适配器的内容,您还应该调用 notifyDataSetChanged()
以确保您的适配器知道您的内容确实发生了变化
关于java - ArrayList Adapter (for ListView) 只显示第一个添加的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39050132/