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.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.listviewaddelementsdynamically_android_examples
.com.MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:text="ADD Values to listview" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Add elements listView" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
ScreenShot