0

我正在制作一个有一个列表视图的 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--;
                    }
                }
            });
4

1 回答 1

1

执行此类操作的标准方法是使用操作栏的操作模式

无论如何,这是一个例子:

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);
    }
}
于 2013-07-30T11:51:41.563 回答