簡體   English   中英

Android:如果ListView中沒有項目,顯示TextView的最佳方法是什么?

[英]Android: what is the best way to show a TextView in case if no item in a ListView?

我需要顯示一個項目列表,這些項目是從數據庫中讀取的,並且有可能沒有項目,在這種情況下,我只想顯示一個TextView說“沒有項目”,我想我可以實現通過使用相對布局,列表和文本都位於父級的中心,它們交替顯示,但是還有什么方法比這更好嗎?

謝謝!

比爾·莫特(Aledam)

您可以隨時調用AdapterView對象上的AdapterView.setEmptyView(View v)來附加要用作空視圖的視圖。

摘錄如下:

 empty = (TextView)findViewById(R.id.empty1);
  list = (ListView)findViewById(R.id.list1);

  list.setEmptyView(empty);

確保將ListView和TextView保留在同一父級中。

有關詳細說明,請參閱

如果您使用的是ListActivity,則這是默認行為。 如果不是,則可以將ListView可見性設置為GONE,將TextView可見性設置為VISIBLE。

阿利丹是對的。 這是一個支持他回答的示例XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    <ListView 
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        />
    <TextView 
        android:id="@id/android:empty" 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:textColor="@drawable/red"
        android:gravity="center_vertical|center_horizontal"
        android:textStyle="bold"
        android:text="@string/error_no_groups" 
        />
</LinearLayout>

Android開發人員網站上的第一個教程介紹了如何執行此操作: http : //developer.android.com/resources/tutorials/notepad/notepad-ex1.html

(看步驟4)

片段:

  • 可以將ListView和TextView視為兩個替代視圖,一次只能顯示其中一個。 如果有要顯示的注釋,則將使用ListView;如果沒有注釋,則將顯示TextView(其默認值為“無注釋!”在res / values / strings.xml中定義為字符串資源)。要顯示的所有注釋。
  • 當ListAdapter沒有ListView的數據時,將自動使用ID為空的View。 默認情況下,ListAdapter知道要查找此名稱。 或者,您可以通過使用ListView上的setEmptyView(View)來更改默認的空視圖。

暫無
暫無

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

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