簡體   English   中英

用ArrayList適配器填充ListView不起作用-有項目但沒有顯示

[英]Populating a ListView with an ArrayList Adapter isn't working - items are there but not being displayed

編輯3我正在提交一個新問題,因為我已經意識到這里的原始問題實際上不是問題。

因此,我有一個片段,可從應用程序的內部存儲中獲取文件,然后在ListView中列出它們。 我正在使用一個ArrayList作為文件名,以及一個使用這些項目填充ListView的適配器。 如果我進行調試,我會看到所有項目都像它們應該在數組列表中一樣,但是由於某種原因,它們不會在列表視圖中顯示。 我完全不知道發生了什么,因為我使用完全相同的代碼制作了一個新的測試應用程序,並且它運行良好。

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>

我很困惑。

編輯:我想強調的是文件“即時運行”正在顯示。 默認情況下,該文件位於默認的內部存儲目錄中。 這是我ArrayList中的第一項。 我發現第一個文件被識別並顯示很奇怪,而其余的卻沒有。 即使它們在ArrayList中(通過logcat驗證)。

編輯2:更奇怪。 如果我明確告訴代碼顯示,例如listItem [1],則它可以正常工作。 所以我可能正在討論for循環的問題。

我對您的最后兩行有些懷疑。 嘗試:

ArrayList<String> list = new ArrayList<>();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM