Skip to content

Instantly share code, notes, and snippets.

@redleafar
Last active September 17, 2016 22:53
Show Gist options
  • Save redleafar/b66bfea9557aba250453eb598669d189 to your computer and use it in GitHub Desktop.
Save redleafar/b66bfea9557aba250453eb598669d189 to your computer and use it in GitHub Desktop.
Change list dynamically
package in.wptrafficanalyzer.additemsdynamically;
 
import java.util.ArrayList;
 
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
 
/** Note that here we are inheriting ListActivity class instead of Activity class **/
public class MainActivity extends ListActivity {
 
    /** 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;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        /** Setting a custom layout for the list activity */
        setContentView(R.layout.main);
 
        /** Reference to the button of the layout main.xml */
        Button btn = (Button) findViewById(R.id.btnAdd);
 
        /** Defining the ArrayAdapter to set items to ListView */
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
 
        /** Defining a click event listener for the button "Add" */
        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText edit = (EditText) findViewById(R.id.txtItem);
                list.add(edit.getText().toString());
                edit.setText("");
                adapter.notifyDataSetChanged();
            }
        };
 
        /** Setting the event listener for the add button */
        btn.setOnClickListener(listener);
 
        /** Setting the adapter to the ListView */
        setAdapter(adapter);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment