如何使用操作栏按钮动态添加到ListView

时间:2014-08-02 14:28:19

标签: android listview

我想动态地将项目添加到Android中的ListView。但是,我希望在用户按下操作栏按钮时完成此操作。根据我的发现,要做到这一点,需要扩展Android不支持的ListActivityActionBarActivity。我怎么办呢。这是我的MainActivity代码(现在只扩展ActionBarActivity):

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;


public class MainActivity extends ActionBarActivity {

     /** Items entered by the user is stored in this ArrayList variable */
    ArrayList<String> list = new ArrayList<String>();

    /** Declaring an ArrayAdapter to set items to ListView */
    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,list);
        setListAdapter(adapter);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_new:
                addListElement();
                return true;
            case R.id.action_settings:

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


    private void addListElement() {
        // TODO Auto-generated method stub

    }
}

1 个答案:

答案 0 :(得分:1)

activity_main.xml添加列表视图中..然后使用如下...

ListView lv = (ListView) findViewById(R.id.listViewId);
lv.setAdapter(adapter);

删除setListAdapter(adapter);

private void addListElement(String value) {

    list.add(value);
    adapter.notifyDataSetChanged();

    }

OR

private void addListElement(String value) {

adapter.add(value);

}