Элемент ListView не найден

Мое приложение использует полноэкранный режим ландшафта и панель навигации. я использую listView в моем приложении вместе с edittext, edittext это строка поиска, которая будет искать listview, Оба listview и edittext находятся в ящике навигации. Но когда нет элемента списка, соответствующего искомому слову, listview становится пустым.

Так как же я могу добавить сообщение "Элемент не найден" вместо пустого listview ?

Я много искал в интернете и нашел метод setEmptyView(); но я не мог этого понять и, следовательно, он не работает. Пожалуйста, помогите мне! Может быть, этот вопрос уже задан здесь, но, пожалуйста, дайте мне простое объяснение.

Вот мой код:

MainActivity.java

public class MainActivity extends FragmentActivity {
final String[] data = {"Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Flourine","Noen","Sodium","Magnesium","Aluminium","Silicon","Phosphorous","Sulphur","Chlorine","Argon","Potassium","Calcium","Scandium","Titanium","Vanadium","Chromium","Manganese","Iron","Cobalt","Nickel","Copper","Zinc","Gallium","Germanium","Arsenic","Selenium","Bromine","Krypton","Rubidium","Strontium","Yttrium","Zirconium","Niobium","Molybdenum","Technetium","Ruthenium","Rhodium","Palladium","Silver","Cadmium","Indium","Tin","Antimony","Tellurium"};
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
    final EditText searchBar = (EditText) findViewById(R.id.searchbar);
    final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
    final ListView navList = (ListView) findViewById(R.id.left_drawer);
    final LinearLayout linearLayout = (LinearLayout)findViewById(R.id.left_drawer_layout);
    navList.setAdapter(adapter);

    searchBar.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {

            MainActivity.this.adapter.getFilter().filter(cs);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {
        }
    });

    //the code below will automatically close the keyboard when the user will touch the listview

    navList.setOnScrollListener(new AbsListView.OnScrollListener() {
        public void onScrollStateChanged(AbsListView view, int scrollState) {

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(navList.getWindowToken(), 0);
        }

        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    });


  }

}

mainactivity.xml

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:background="#000000"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Swipe from the left to open the drawer"
        android:id="@+id/textView"
        android:layout_gravity="center" />
</FrameLayout>

<LinearLayout
    android:id="@+id/left_drawer_layout"
    android:layout_height="fill_parent"
    android:layout_width="240dp"
    android:background="#111"
    android:orientation="vertical"
    android:layout_gravity="start" >

    <EditText
        android:id="@+id/searchbar"
        android:layout_width="230dp"
        android:layout_height="40dp"
        android:textColor="#bfc2d1"
        android:singleLine="true"
        android:padding="10dp"
        android:background="@drawable/search_bar"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="3dp"
        android:imeOptions="flagNoExtractUi"
        android:hint=" search" >
    </EditText>

    <TextView
        android:id="@+id/notfound"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        style="@android:style/TextAppearance.Medium"
        android:gravity="center">
    </TextView>

    <ListView android:id="@+id/left_drawer"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</LinearLayout>

</android.support.v4.widget.DrawerLayout>

3 ответа

Решение

Да, вы правильно упомянули о setEmptyView(), вы должны использовать его, если хотите отображать пустое сообщение всякий раз, когда ListView становится пустым.

Теперь вот макет xml, и код показывает, как точно использовать setEmptyView.

<LinearLayout
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/layoutTitlebar" >

    <ListView
        android:id="@+id/listViewFriends"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/friendBGColor"
        android:cacheColorHint="#00000000" >
    </ListView>

    <TextView
        android:id="@+id/empty"
        style="@android:style/TextAppearance.Large"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="@string/strNoRecordsFound" >
    </TextView>

</LinearLayout>

Теперь вы должны установить это пустое представление (т.е. TextView) на ListView, используя:

ListView listViewFriends = (ListView) findViewById(R.id.listViewFriends);
// set your adapter here
// set your click listener here
// or whatever else
listViewFriends.setEmptyView(findViewById(R.id.empty));

Этот метод - все, что вам нужно

http://developer.android.com/reference/android/widget/AdapterView.html

Имейте в виду, что он принимает представление, поэтому вы должны надуть макет и заполнить любой / весь текст, который у вас там есть, самостоятельно.

РЕДАКТИРОВАТЬ:

Давайте предположим, что у вас есть макет с именем empty_text, например:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:text="There are no entries in this list"
        android:gravity="center"/>
</LinearLayout>

Подсказка: я записал строку в качестве примера, учел предупреждение IDE и использовал строковый идентификатор для I18n

Теперь вы должны использовать этот код, чтобы все это работало с ListView:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View emptyTextView = inflater.inflate(R.layout.empty_text, null, false);
listView.setEmptyView(emptyTextView);

Этот код предполагает, что вы выполняете внутри Activity, но на случай, если вы не планируете вставлять его в Activity, любой экземпляр Context будет работать.

Это должно быть так.

ListView lv = (ListView)findViewById(android.R.id.list);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
lv.setEmptyView(emptyText);

Тогда ваше представление списка будет автоматически использовать это представление, когда его адаптер пуст.

Детальное решение:

Планировка:

<ListView
android:id="@+id/listViewFriends"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="@color/friendBGColor"
android:cacheColorHint="#00000000">
</ListView>

<TextView
android:id="@+id/empty"
android:text="@string/strNoRecordsFound"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
style="@android:style/TextAppearance.Large"
android:gravity="center">
</TextView>
</LinearLayout>

Файл класса:

ListView listViewFriends = (ListView) findViewById(R.id.listViewFriends);
listViewFriends.setEmptyView(findViewById(R.id.empty));

Источник

Другие вопросы по тегам