从菜单调用适配器上的notifyDataSetChanged()

时间:2014-12-28 01:33:28

标签: android listview refresh adapter

我有一个应用程序,它创建了一个名为StabelArrayAdapter的自定义数组适配器,它基于ArrayAdapter类。它是在活动的onCreate()方法中创建的,我希望在视图更改时从菜单中刷新它。我无法从菜单访问适配器,我无法将其公开。

如何从菜单刷新列表视图?

格雷格

public void onCreate(Bundle savedInstanceState) {
    final StableArrayAdapter adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, listNames);
    listview.setAdapter(adapter);
}

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.list_add:
                Toast.makeText(getApplicationContext(), "Add new list" , Toast.LENGTH_LONG)
                .show();
                return true;
            case R.id.list_delete:
                //change data here
                final ListView listview = (ListView) findViewById(R.id.ListLists);

                //--> Cannot resolve symbol 'adapter'

                adapter.notifyDataSetChanged();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
}

1 个答案:

答案 0 :(得分:1)

您需要使适配器成为类成员,然后您可以引用它。

private StableArrayAdapter adapter;

public void onCreate(Bundle savedInstanceState) {
    adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, listNames);
    listview.setAdapter(adapter);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case R.id.list_add:
            Toast.makeText(getApplicationContext(), "Add new list" , Toast.LENGTH_LONG)
            .show();
            return true;
        case R.id.list_delete:
            //change data here
            final ListView listview = (ListView) findViewById(R.id.ListLists);
            adapter.notifyDataSetChanged();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}