【发布时间】:2016-12-27 06:28:01
【问题描述】:
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());
仅显示模板文件[1]。同样,如果我这样做:
templateList.add(templateFiles[0].getName());
templateList.add(templateFiles[1].getName());
仅显示模板文件[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>
【问题讨论】:
-
你也可以发布你的xml代码吗?
-
尝试在列表中添加一些简单的字符串("a","b","c"...),而不是templateFiles[i],看看问题是否仍然存在。
-
您的代码似乎没问题。我假设您的
ListView已正确填充,但不知何故只有第一项可见。请在您的setAdapter()呼叫后通过在您的ListView实例上呼叫getCount()进行确认。如果是这种情况,请发布您的布局的 XML 代码。 -
好的,xml 已发布。 @Leo.Han - 放入简单字符串仍然存在仅显示第一个(在本例中为“a”)的问题。
-
getCount 结果为 8。这是正确的,因为我在内部存储中有 8 个文件。
标签: java android listview arraylist