【android】ListView 中添加按鈕,動態刪除添加ItemView的操作

來源:互聯網
上載者:User

1、要實現添加按鈕的操作,必須自訂Adapter,使用Button View的setTag()方法,將Button所屬的位置設定到tag當中

2、要實現動態添加刪除ItemView的操作,必須首先調整調整Adapter所繫結資料源,然後調用Adapter的notifyDataSetChanged()方法

 

3、在adapter中,View的事件不能顯示得對View本身操作,例如:

listView.addBnt.setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View v) {                // TODO Auto-generated method stub                //配合上面的setTag,可以使用v來操縱控制項,而不必用listView.addBnt,                //如果要在事件中操縱listView.addBnt,要求必須是final的                //可以利用poi刪除mchannelList對應的元素,然後adapter notify,然後listView重新整理,可以隱藏選中的item                int poi = Integer.parseInt(v.getTag().toString());                Channel channel = mchannelList.get(poi);                DBUtil.insertChannel(mcontext, channel);                                Button bnt = (Button)v;                bnt.setText("已添");                bnt.setTextColor(R.color.black);                bnt.setClickable(false);                                new AlertDialog.Builder(mcontext).setTitle("Info")                    .setMessage("添加成功").setPositiveButton("OK", new DialogInterface.OnClickListener() {                                                @Override                        public void onClick(DialogInterface dialog, int which) {                            // TODO Auto-generated method stub                            Task task = new Task(Task.TASK_CHANNEL_LIST, null);                            MainService.allTask.add(task);                            Log.i(TAG, "onClick:add a task - TAST_CHANNEL_LIST");                        }                    }).create().show();            }});

不能對listView.addBnt操作,若要強行操作,要求是final類型,這是不可能的。

 

例子:

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;        }             }}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.