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

后端 未结 7 2041
情歌与酒
情歌与酒 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:47

    First, you have to add a ListView, an EditText and a button into your activity_main.xml.

    Now, in your ActivityMain:

    private EditText editTxt;
    private Button btn;
    private ListView list;
    private ArrayAdapter<String> adapter;
    private ArrayList<String> arrayList;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        editTxt = (EditText) findViewById(R.id.editText);
        btn = (Button) findViewById(R.id.button);
        list = (ListView) findViewById(R.id.listView);
        arrayList = new ArrayList<String>();
    
        // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
        // and the array that contains the data
        adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);
    
        // Here, you set the data in your ListView
        list.setAdapter(adapter);
    
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
    
                // this line adds the data of your EditText and puts in your array
                arrayList.add(editTxt.getText().toString());
                // next thing you have to do is check if your adapter has changed
                adapter.notifyDataSetChanged();
            }
        });
    }
    

    This works for me, I hope I helped you

    0 讨论(0)
提交回复
热议问题