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

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

    Code for MainActivity.java file.

    public class MainActivity extends Activity {
    
        ListView listview;
        Button Addbutton;
        EditText GetValue;
        String[] ListElements = new String[] {
            "Android",
            "PHP"
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            listview = (ListView) findViewById(R.id.listView1);
            Addbutton = (Button) findViewById(R.id.button1);
            GetValue = (EditText) findViewById(R.id.editText1);
    
            final List < String > ListElementsArrayList = new ArrayList < String >
                (Arrays.asList(ListElements));
    
    
            final ArrayAdapter < String > adapter = new ArrayAdapter < String >
                (MainActivity.this, android.R.layout.simple_list_item_1,
                    ListElementsArrayList);
    
            listview.setAdapter(adapter);
    
            Addbutton.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
                    ListElementsArrayList.add(GetValue.getText().toString());
                    adapter.notifyDataSetChanged();
                }
            });
        }
    }
    

    Code for activity_main.xml layout file.

    
    
      

    ScreenShot

提交回复
热议问题