Saturday, 11 October 2014

ListView Databinding, add remove items

yes, we know Listview a component to bind list of items, if items are more it will show items in scrollview behaviour.

in this demo: we added 2 string-array files(awords,bwords). awords added at design time, and bwords are added at runtime(button click--Bind items).

blistwords items are,we can't get at class declaration time because bwords are not available resources are loaded. so added that onclick event.

public class MainActivity extends Activity implements OnClickListener,OnItemClickListener
{
    Button addbtn,delbtn;
    ListView listview;
    EditText edt;
    ArrayList<String> al;
    ArrayAdapter<String> arrayadapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt=(EditText)findViewById(R.id.editText1);
listview=(ListView)findViewById(R.id.listView1);
addbtn=(Button)findViewById(R.id.button1);
delbtn=(Button)findViewById(R.id.button2);
al=new ArrayList<String>();
arrayadapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,al);
listview.setAdapter(arrayadapter);
addbtn.setOnClickListener(this);
delbtn.setOnClickListener(this);
listview.setOnItemClickListener(this);
}
Add and remove items

public void onClick(View v)
{
if(v==addbtn)
{
String item=edt.getText().toString().trim();
if(item.length()>0)
{
al.add(item);
arrayadapter.notifyDataSetChanged();
edt.setText("");
edt.requestFocus();
}
}
if(v==delbtn)
{
String item=edt.getText().toString().trim();
if(item.length()>0)
{
al.remove(item);
arrayadapter.notifyDataSetChanged();
edt.setText("");
edt.requestFocus();
}
}
}
AdapterView event : this event supports of listview, spinner...ect

public void onItemClick(AdapterView<?> parent, View view, int position,long id)
{
TextView tv=(TextView)view;
String item=tv.getText().toString();
edt.setText(item);
}

No comments:

Post a Comment