[Android] Add button in listview to dynamically Delete the operation of adding itemview

Source: Internet
Author: User

1. To add a button, you must customize the adapter and use the settag () method of the button view to set the position of the button to the tag.

2. To add and delete itemview dynamically, you must adjust the data source bound to the adapter and then call the notifydatasetchanged () method of the adapter.

 

3. In the adapter, view events cannot be displayed as operations on the view itself. For example:

Listview. addbnt. setonclicklistener (New onclicklistener () {@ override public void onclick (view v) {// todo auto-generated method stub // with the above settag, you can use V to manipulate the control, instead of using listview. addbnt, // If You Want To manipulate listview in the event. addbnt, which must be final // you can use poi to delete the elements corresponding to mchannellist, then adapter policy, and then refresh the listview to hide the selected item int poi = integer. parseint (v. gettag (). tostring (); channel = mchannellist. get (POI); dbutil. insertchannel (mcontext, Channel); button BNT = (button) V; BNT. settext ("added"); BNT. settextcolor (R. color. black); BNT. setclickable (false); New alertdialog. builder (mcontext ). settitle ("info "). setmessage ("added successfully "). setpositivebutton ("OK", new dialoginterface. onclicklistener () {@ override public void onclick (dialoginterface dialog, int which) {// todo auto-generated method stub task = new task (task. task_channel_list, null); mainservice. alltask. add (task); log. I (TAG, "onclick: Add a task-tast_channel_list ");}}). create (). show ();}});

You cannot perform operations on listview. addbnt. If you want to force the operation, the operation must be of the final type, which is impossible.

 

Example:

package com.jason.joysmsyd; import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; import android.app.ListActivity;import android.content.Intent;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.Window;import android.view.View.OnClickListener;import android.widget.BaseAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.TextView; public class SendMain extends ListActivity implements OnClickListener{     Button buttonMessage,buttonContact,buttonHistory;    EditText textMessage;         List<Map<String,String>> contacts = new ArrayList<Map<String,String>>();                   @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        this.requestWindowFeature(Window.FEATURE_NO_TITLE);                 this.setContentView(R.layout.layout_send);                 buttonMessage = (Button) this.findViewById(R.id.ButtonMessage);        buttonContact = (Button) this.findViewById(R.id.ButtonContact);        buttonHistory = (Button) this.findViewById(R.id.ButtonHistory);                 textMessage = (EditText)this.findViewById(R.id.EditTextMessage);        textMessage.setText(this.getIntent().getExtras().getString("message"));         }     public void onClick(View v) {        // TODO Auto-generated method stub        switch(v.getId()){        case R.id.ButtonMessage:            this.finish();            break;        case R.id.ButtonContact:        {            Intent intent = new Intent();            intent.setAction("com.jason.action.contact");            this.startActivityForResult(intent, 0);        }            break;        case R.id.ButtonHistory:        {            Intent intent = new Intent();            intent.setAction("com.jason.action.history");            this.startActivityForResult(intent, 1);        }            break;        }             }          protected void onActivityResult(int requestCode, int resultCode, Intent data) {        // TODO Auto-generated method stub        super.onActivityResult(requestCode, resultCode, data);         if (requestCode == 0 && resultCode == RESULT_OK) {            this.getcontactFromString(data.getExtras().getString(                    UserSelectActivity.RETURN_LIST));            bindDataToList();        }    }     private void getcontactFromString(String data) {        if (data == null || data.length() == 0) {            return;        }                  String[] arrayContact = data.split("#");        for (String singleContact : arrayContact) {            if (singleContact != null && singleContact.length() > 0) {                String[] props = singleContact.split(":");                if (props.length == 2) {                    Map<String,String> contact = new HashMap<String,String>();                    contact.put("name", props[0]);                    contact.put("phone", props[1]);                    contacts.add(contact);                 }            }         }             }         private void bindDataToList(){        this.setListAdapter(new MyAdapter());    }         public class MyAdapter extends BaseAdapter{         public int getCount() {            // TODO Auto-generated method stub            return contacts.size();        }         public Object getItem(int position) {            // TODO Auto-generated method stub            return contacts.get(position);        }         public long getItemId(int position) {            // TODO Auto-generated method stub            return position;        }          public View getView(int position, View convertView, ViewGroup parent) {            // TODO Auto-generated method stub            LayoutInflater inflater = SendMain.this.getLayoutInflater();             final View view = inflater.inflate(R.layout.layout_user_item, null);             final TextView textPhone = (TextView) view.findViewById(R.id.text1);             final TextView textName = (TextView) view.findViewById(R.id.text2);             Button button = (Button)view.findViewById(R.id.buttonDelete);                          textPhone.setText(contacts.get(position).get("phone"));             textName.setText(contacts.get(position).get("name"));                           button.setTag( position);                           button.setOnClickListener(new OnClickListener(){                 public void onClick(View v) {                    // TODO Auto-generated method stub                    int position = Integer.parseInt(v.getTag().toString());                    contacts.remove(position);                    MyAdapter.this.notifyDataSetChanged();                     //                  SendMain.this.getListView().refreshDrawableState();                }});                                                                   return view;        }             }}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.