2015-03-03 3 views
0

Я пытаюсь добавить больше элементов в список в проекте Android. Это мой код, я использую:Android ListView добавляет больше элементов notifyDataSetChanged() не работает

public class NewsFeedActivity extends ListActivity implements FetchDataListener{ 

boolean loadingMore = false; 

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

    SharedPreferences shared = getSharedPreferences(MainActivity.class.getSimpleName(),Context.MODE_PRIVATE); 
    @SuppressWarnings("unused") 
    String storedUID = (shared.getString(UID, "")); 

    final ListView list = (ListView)findViewById(android.R.id.list); 
    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); 
    swipeLayout.setColorSchemeResources(R.color.black, R.color.white, R.color.black, R.color.white); 
    swipeLayout.setOnRefreshListener(new OnRefreshListener() { 

     @Override 
     public void onRefresh() { 
      new Handler().postDelayed(new Runnable() { 
        @Override public void run() { 
         swipeLayout.setRefreshing(false); 
         loadingMore = true; 
         initView(); 
        } 
       }, 1000); 

     } 

    }); 

    list.setOnScrollListener(new OnScrollListener(){ 

     private int currentFirstVisibleItem; 
     private int currentVisibleItemCount; 
     private int totalItem; 

     @Override 
      public void onScrollStateChanged(AbsListView view, int scrollState) { 
       this.isScrollCompleted(); 
      } 

      private void isScrollCompleted() { 
      // TODO Auto-generated method stub 
       int lastInScreen = currentFirstVisibleItem + currentVisibleItemCount;  
       if((lastInScreen == totalItem) && !(loadingMore)){  
        //Toast.makeText(getApplicationContext(), "Loading more...", Toast.LENGTH_LONG).show(); 
        loadingMore = true; 
        initView(); 


       } 
      } 



     @Override 
      public void onScroll(AbsListView view, int firstVisibleItem, 
      int visibleItemCount, int totalItemCount) { 

      this.currentFirstVisibleItem = firstVisibleItem; 
      this.currentVisibleItemCount = visibleItemCount; 
      this.totalItem = totalItemCount; 
     } 

      }); 


    initView(); 

} 

и вот две другие функции, я использую для вызова списка в:

private void initView() { 
    // show progress dialog 
    if(!loadingMore == true){ 
    dialog = ProgressDialog.show(this, "", "Loading..."); 
    } 
    String url = SERVER_URL+getBlackCards; 
    FetchDataTask task = new FetchDataTask(this); 
    task.execute(url); 
} 

public void onFetchComplete(List<Application> data) { 
    // dismiss the progress dialog 

    if(dialog != null) dialog.dismiss(); 
    // create new adapter 
    ApplicationAdapter adapter = new ApplicationAdapter(this, data); 
    // set the adapter to list 

    setListAdapter(adapter); 

    if(loadingMore == true){ 
     adapter.notifyDataSetChanged(); 
    } 

    loadingMore = false; 
} 

Текущее поведение является по существу только обновления, где все элементы заменяются, и я прокручиваюсь до верхней части списка. После некоторого осмотра я нашел много примеров, которые использовали notifyDataSetChanged() для добавления элементов, но, похоже, это не повлияло на меня.

+0

Вы не добавляя новые данные адаптера, вы просто создать новый adpater с новыми данными. –

ответ

1

Текущее поведение является по существу только обновления, где все элементы заменяются и я прокручивается обратно к верхней части списка

Потому что здесь:

ApplicationAdapter adapter = new ApplicationAdapter(this, data); 
setListAdapter(adapter); 

Каждый раз, создавая новый объект класса adapter вместо добавления новых элементов в текущий адаптер ListView.

ли как:

1. Создание ApplicationAdapter объекта на уровне класса:

ApplicationAdapter adapter; 
public void onFetchComplete(List<Application> data) { 
    // dismiss the progress dialog 

    if(dialog != null) dialog.dismiss(); 
    // create new adapter 
    if(adapter==null){ 
    adapter = new ApplicationAdapter(this, data); 
    // set the adapter to list 
    setListAdapter(adapter); 
    }else{ 
     // update current adapter 
    } 
    loadingMore = false; 
} 

2. Создать метод addAllItems в ApplicationAdapter классе:

public void addAllItems(List<Application> data){ 
    this.data.addAll(data); 
    this.notifyDataSetChanged(); 
} 

3. Позовите addAllItems в еще части onFetchComplete метода:

adapter.addAllItems(data); 
+0

Абсолютно пятно на! Большое спасибо :) – jampez77

Смежные вопросы