Thursday 12 September 2013

Dynamically Adding the List item through edit text

How to add list items dynamically using edit text


Here we'll add List items dynamically by using edit text and a button.

1.activity_main.xml

<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" >

    <EditText
        android:id="@+id/edt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edt"
        android:text="Add To list" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >
    </ListView>

</RelativeLayout>

2.MainActivity.java

package com.sri.listview;

import android.app.Activity;
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;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
ListView lvList;
EditText ed;
Button bt;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed = (EditText) findViewById(R.id.edt);
bt = (Button) findViewById(R.id.btn);
lvList = (ListView) findViewById(R.id.listView1);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_list_item_1);

bt.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String str = ed.getText().toString();
if (str != null)
adapter.add(str);
ed.setText("");
Toast.makeText(getApplicationContext(), "successfully added", Toast.LENGTH_SHORT).show();
}
});
lvList.setAdapter(adapter);
}

}

3.That's all now run your project.this will add the text item entered  in edit text to the list view.

No comments:

Post a Comment