How do you dynamically add elements to a ListView on Android?

后端 未结 7 2033
情歌与酒
情歌与酒 2020-11-22 08:47

Can anyone explain or suggest a tutorial to dynamically create a ListView in android?

Here are my requirements:

  • I should be able to dynamically add new e
7条回答
  •  清酒与你
    2020-11-22 09:22

    If you want to have the ListView in an AppCompatActivity instead of ListActivity, you can do the following (Modifying @Shardul's answer):

    public class ListViewDemoActivity extends AppCompatActivity {
        //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
        ArrayList listItems=new ArrayList();
    
        //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
        ArrayAdapter adapter;
    
        //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
        int clickCounter=0;
        private ListView mListView;
    
        @Override
        public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.activity_list_view_demo);
    
            if (mListView == null) {
                mListView = (ListView) findViewById(R.id.listDemo);
            }
    
            adapter=new ArrayAdapter(this,
                    android.R.layout.simple_list_item_1,
                    listItems);
            setListAdapter(adapter);
        }
    
        //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
        public void addItems(View v) {
            listItems.add("Clicked : "+clickCounter++);
            adapter.notifyDataSetChanged();
        }
    
        protected ListView getListView() {
            if (mListView == null) {
                mListView = (ListView) findViewById(R.id.listDemo);
            }
            return mListView;
        }
    
        protected void setListAdapter(ListAdapter adapter) {
            getListView().setAdapter(adapter);
        }
    
        protected ListAdapter getListAdapter() {
            ListAdapter adapter = getListView().getAdapter();
            if (adapter instanceof HeaderViewListAdapter) {
                return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
            } else {
                return adapter;
            }
        }
    }
    

    And in you layout instead of using android:id="@android:id/list" you can use android:id="@+id/listDemo"

    So now you can have a ListView inside a normal AppCompatActivity.

提交回复
热议问题