2014-01-23 3 views
6

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

Так как я могу добавить сообщение «Item not found» вместо пустого 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> 
+0

Мысль вы новичок на этом сайте, и хотя вы 14, вы опубликовали подробный вопрос , Большой! Кстати, вы просто пропустили код макета проводки. –

+0

Благодарим за быстрый ответ. Должен ли я отправить файл Xml? –

+0

Да, его можно так лучше предложить! –

ответ

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)); 
+0

@ user3227476 пробовал полный код? –

+0

@ user3227476 вы не выбрали пустой вид и еще не установили его в ListView. –

+0

@ChinmayDabke, поэтому я получил вас точно, вы сделали меня дураком, написав, что вы новичок в этом сайте и 14-летнем разработчике. Спасибо за это. Примите ответ прямо сейчас! –

1

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

http://developer.android.com/reference/android/widget/AdapterView.html#setEmptyView(android.view.View)

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

EDIT:

Давайте предположим, что вы макет под названием «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 будет работать.

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

+0

На самом деле я читал документы, но это так сложно. Не могли бы вы помочь мне с кодом? –

+1

Вы читали вопрос полностью? Я сомневаюсь, потому что он уже упомянул что-то относительно 'setEmptyView()' –

+0

Можете ли вы, пожалуйста, помочь мне с кодом? –

0
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)); 

Source