第二次设置适配器时未显示ListView

时间:2014-11-25 23:45:13

标签: android listview android-activity android-arrayadapter

我有两个不同的活动,我之间改变。但是,当我进入第二个活动并按回ListView时,不会显示。我似乎无法找到问题所在。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    currentLayout = R.layout.activity_main;
    db = new TodoDbHelper(this);
    todos = db.getAllTodos();
    nrOfTodos = todos.size();

    //For ListView
    mListView = (ListView) findViewById(R.id.gradientBackground);
    mAdapter = new TodoAdapter<String>(this, R.layout.text_view_item_default);
    mListView.setAdapter(mAdapter);

    //Calculate height of screen
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;
    listItemSize = height/10;
    SCREEN_WIDTH = width;        

    createTodoItems();

}

public void createTodoItems() {
    refresh();
    mAdapter.clear();
    for(int i = 0; i < nrOfTodos; i++) {
        String title = todos.get(i).getTitle();

        mAdapter.add(title);
        //System.out.println(title);
        //System.out.println(mAdapter);

    }
    mListView.setAdapter(mAdapter);         
    ImageButton b = (ImageButton) findViewById(R.id.addButton);
    b.bringToFront();
}

public void refresh() {
    todos = db.getAllTodos();
    nrOfTodos = todos.size();
}

@Override
public void onBackPressed() {
    System.out.println("" + this.findViewById(android.R.id.content).getRootView());
    System.out.println("" + currentLayout);
    if(R.layout.activity_add_todo == currentLayout) {
        setContentView(R.layout.activity_main);
        currentLayout = R.layout.activity_main;

        createTodoItems();
        Log.d("onBackPressed", "We're going back.");
    }

}

我做同样的事情&#34; createTodoItems()&#34;这两个时间,但第二次似乎并不重要。

在第二个createTodoItems()之后,似乎mAdapter是相同的。 mAdapter中的值仍然相同。

添加新项目时出现同样的问题。它只是不会从ListView中呈现任何内容。

1 个答案:

答案 0 :(得分:1)

尝试添加此函数notifyDataSetChanged(),可能有帮助:

public void createTodoItems() {
   refresh();
   mAdapter.clear();
   for(int i = 0; i < nrOfTodos; i++) {
      title = todos.get(i).getTitle();

      mAdapter.add(title);
      //System.out.println(title);
      //System.out.println(mAdapter);

   }
   mListView.setAdapter(mAdapter);  
   mAdapter.notifyDataSetChanged();   
   ImageButton b = (ImageButton) findViewById(R.id.addButton);
   b.bringToFront();
}