2013-07-30 190 views
0

我正在製作一個有一個List視圖的Android應用程序。在第一次選擇特定項目時,我已更改該項目的文本顏色。列表視圖允許多項選擇。現在有一個名爲「完成」的文本視圖。當用戶點擊「完成」時,應該刪除未從列表視圖中選擇的項目。我該怎麼辦?以下是我的代碼...從列表視圖中刪除多個項目,除了所選項目

tvDone.setOnClickListener(new OnClickListener() { 

       @SuppressWarnings("deprecation") 
       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        if(colorRow > 0) 
        { 
        AlertDialog builder = new AlertDialog.Builder(NewFriendList.this).create(); 
        builder.setTitle("Save to List"); 
        builder.setMessage("Do You Want to Save?"); 
        builder.setButton("Save", new DialogInterface.OnClickListener() 
        { 

         public void onClick(DialogInterface dialog, int which) 
         { 
          tvEdit.setVisibility(View.VISIBLE); 
          tvClear.setVisibility(View.VISIBLE); 
          tvDelete.setVisibility(View.VISIBLE); 


         } 
        }); 

        builder.setButton2("Cancel", new DialogInterface.OnClickListener() 
        { 
         public void onClick(DialogInterface dialog, int which) 
         { 
          chkText.setTextColor(Color.BLACK); 
          tvEdit.setVisibility(View.INVISIBLE); 
          tvClear.setVisibility(View.INVISIBLE); 
          tvDelete.setVisibility(View.INVISIBLE); 
         } 

         }); 
         builder.show(); 
        } 

        else 
         Toast.makeText(getBaseContext(), "Select Friends", 1000).show(); 
      } 
      }); 

      lvDialog.setOnItemClickListener(new OnItemClickListener() { 

       @Override 
       public void onItemClick(AdapterView<?> arg0, View arg1, 
         int arg2, long arg3) { 
        // TODO Auto-generated method stub 

        checked = lvDialog.getCheckedItemPositions(); 
        chkText = (CheckedTextView) arg1.findViewById(R.id.txt); 

        if(checked.get(arg2)) 
        { 
         chkText.setTextColor(Color.CYAN); 
         colorRow ++; 
        } 
        else 
        { 
         chkText.setTextColor(Color.BLACK); 
         colorRow--; 
        } 
       } 
      }); 

回答

1

執行此類操作的標準方法是使用操作欄的Action mode

不管怎樣,下面是一個例子:

的DataModel:這暴露了數據處理方法本地代碼。在這裏它只是使用內存中的數據結構,但在實際應用中,它可以由數據庫或Web服務或其他東西支持。

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Set; 

public class DataModel { 
    private static DataModel ourInstance = new DataModel(); 

    private final List<String> mPersons; 
    private final HashMap<String,Set<String>> mGroups; 

    public static DataModel getInstance() { 
     return ourInstance; 
    } 

    private DataModel() { 
     mPersons = new ArrayList<String>(); 
     mGroups = new HashMap<String, Set<String>>(); 

     for (int i = 0; i < 50; i++){ 
      mPersons.add("person_"+i); 
     } 
    } 

    public void updateGroup(String oldName, String newName, Set<String> members){ 
     assert newName != null && !newName.isEmpty() && members != null : "data must not be null or empty"; 

     if(oldName != null){ 
      mGroups.remove(oldName); 
     } 

     mGroups.put(newName, members); 
    } 

    public void deleteGroup(String name){ 
     mGroups.remove(name); 
    } 

    public boolean isMember(String groupName, String memberName){ 
     return mGroups.containsKey(groupName) && mGroups.get(groupName).contains(memberName); 
    } 

    public List<String> getGroups(){ 
     List<String> groups = new ArrayList<String>(); 

     for (String s : mGroups.keySet()){ 
      groups.add(s); 
     } 

     return groups; 
    } 

    public List<String> getMembersOf(String groupName){ 
     List<String> members = new ArrayList<String>(); 

     if(mGroups.containsKey(groupName)){ 
      members.addAll(mGroups.get(groupName)); 
     } 

     return members; 
    } 

    public List<String> getPersons(){ 
     List<String> persons = new ArrayList<String>(); 
     persons.addAll(mPersons); 
     return persons; 
    } 
} 

活動列出數據:長點擊任何項目允許操作模式中,或通過單擊編輯項目。

import android.app.ListActivity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.ActionMode; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.AbsListView; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 

import java.util.ArrayList; 
import java.util.List; 

public class GroupActivity extends ListActivity implements AbsListView.MultiChoiceModeListener, AdapterView.OnItemClickListener { 
    public static final int REQ_CODE_EDIT_GROUP = 101; 

    private List<String> mSelection; 
    private ArrayAdapter<String> mAdapter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     mSelection = new ArrayList<String>(); 
     mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1); 

     mAdapter.addAll(DataModel.getInstance().getGroups()); 

     setListAdapter(mAdapter); 
     getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL); 
     getListView().setMultiChoiceModeListener(this); 
     getListView().setOnItemClickListener(this); 
    } 

    private void refresh(){ 
     mAdapter.clear(); 
     mAdapter.addAll(DataModel.getInstance().getGroups()); 
     mAdapter.notifyDataSetInvalidated(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     MenuItem item = menu.add("New"); 
     item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 
     return super.onCreateOptionsMenu(menu); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     if(item.getTitle().equals("New")){ 
      startEditor(null); 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    private void startEditor(String groupName){ 
     Intent i = new Intent(this,EditorActivity.class); 

     if(groupName != null){ 
      i.putExtra(EditorActivity.KEY_EDIT_GROUP,groupName); 
     } 

     startActivityForResult(i,REQ_CODE_EDIT_GROUP); 
    } 

    @Override 
    public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean checked) { 
     if(checked){ 
      mSelection.add(mAdapter.getItem(i)); 
     }else { 
      mSelection.remove(mAdapter.getItem(i)); 
     } 
    } 

    @Override 
    public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { 
     MenuItem item = menu.add("Delete"); 
     item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 
     return true; 
    } 

    @Override 
    public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { 
     return false; 
    } 

    @Override 
    public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { 
     if(menuItem.getTitle().equals("Delete")){ 

      for (String groupName : mSelection){ 
       DataModel.getInstance().deleteGroup(groupName); 
      } 

      refresh(); 
      actionMode.finish(); 
      return true; 
     }else { 
      return false; 
     } 
    } 

    @Override 
    public void onDestroyActionMode(ActionMode actionMode) { 
     mSelection.clear(); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

     if(requestCode == REQ_CODE_EDIT_GROUP && resultCode == RESULT_OK){ 
      refresh(); 
     }else { 
      super.onActivityResult(requestCode, resultCode, data); 
     } 
    } 

    @Override 
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 
     String groupName = mAdapter.getItem(i); 
     startEditor(groupName); 
    } 
} 

活動編輯數據:允許編輯名稱和選擇等

它有一個佈局:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

<EditText 
    android:id="@+id/edit" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:hint="Group name" 
    android:inputType="text"/> 
    <ListView 
     android:id="@+id/list" 
     android:layout_width="match_parent" 
     android:layout_height="fill_parent" 
     /> 
</LinearLayout> 

而且活動代碼:

import android.app.Activity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.*; 

import java.util.HashSet; 


public class EditorActivity extends Activity { 
    public static final String KEY_EDIT_GROUP = "edit_group"; 

    private EditText mNameEdit; 
    private ListView mListView; 
    private ArrayAdapter<String> mAdapter; 
    private String mOldGroupName; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.editor); 

     mNameEdit = (EditText) findViewById(R.id.edit); 
     mListView = (ListView) findViewById(R.id.list); 

     mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); 

     mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1); 
     mAdapter.addAll(DataModel.getInstance().getPersons()); 
     mListView.setAdapter(mAdapter); 

     mOldGroupName = getIntent().getStringExtra(KEY_EDIT_GROUP); 

     if(mOldGroupName != null){ 
      mNameEdit.setText(mOldGroupName); 

      for (int i = 0 ; i < mAdapter.getCount(); i++){ 
       DataModel dm = DataModel.getInstance(); 
       String member = mAdapter.getItem(i); 

       if(dm.isMember(mOldGroupName,member)){ 
        mListView.setItemChecked(i,true); 
       } 
      } 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     MenuItem item = menu.add("Done"); 
     item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 
     return super.onCreateOptionsMenu(menu); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     if(item.getTitle().equals("Done")){ 

      String newGroupName = mNameEdit.getText().toString(); 

      if(newGroupName == null || newGroupName.isEmpty()){ 
       Toast.makeText(this,"Invalid group name",Toast.LENGTH_LONG).show(); 
       return true; 
      } 

      HashSet<String> selectedMembers = new HashSet<String>(); 
      for (int i = 0 ; i < mAdapter.getCount(); i++){ 
       if(mListView.isItemChecked(i)){ 
        selectedMembers.add(mAdapter.getItem(i)); 
       } 
      } 

      DataModel.getInstance().updateGroup(mOldGroupName,newGroupName,selectedMembers); 

      setResult(RESULT_OK); 
      finish(); 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 
} 
+0

嘿,我試過但不工作...這是我的代碼 \t \t \t \t \t \t \t對(INT C = 0; c

+0

@AnilBhatiya你可以發佈你設置列表視圖使用選擇模式的代碼嗎? –

+0

adapter2 = new ArrayAdapter (getBaseContext(),R.layout.single_row,R.id.txt,arr2); \t \t \t \t lvDialog.setAdapter(adapter2); \t \t \t \t lvDialog.setChoiceMode(ListView。CHOICE_MODE_MULTIPLE); \t \t \t \t adapter2.notifyDataSetChanged(); –