ArrayList Adapter(用于ListView)仅显示第一个添加的项目

the*_*one 5 java android listview arraylist

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"
/>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

templateFiles []数组正确获取内部存储中的8个文件(通过logcat/debugger确认),但只有第一个项目显示在ListView中.这里有一个更清晰的问题:

// If I replace the for loop with this:

    templateList.add(templateFiles[1].getName());
    templateList.add(templateFiles[0].getName());
Run Code Online (Sandbox Code Playgroud)

仅显示templateFiles [1].同样,如果我这样做:

    templateList.add(templateFiles[0].getName());
    templateList.add(templateFiles[1].getName());
Run Code Online (Sandbox Code Playgroud)

仅显示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>
Run Code Online (Sandbox Code Playgroud)

Jor*_*dez 1

如果您要更新适配器的内容,您notifyDataSetChanged()也应该调用以确保您的适配器知道您的内容确实发生了更改

  • 如果在设置适配器后更新数据集,则应调用“notifyDataSetChanged()”。这里完全没有必要。 (3认同)