保存动态添加到列表视图的项目

时间:2015-02-20 11:35:39

标签: android android-listview android-edittext

我有一个列表视图,其中我使用了一个edittext字段,它将项目添加到列表视图中。但是,当我单击关闭并返回列表视图时,它不会保存我添加的任何项目。我已经研究了实现这个的方法,因为我的项目不是String我不确定如何做到这一点,否则我会使用sharedprefrences。我的代码低于任何帮助将不胜感激。

public class ConversationView extends Activity {
    EditText write_message;
    Button post_message_button;


    Integer threadId;

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

        Intent intent = getIntent();
        String thread = intent.getStringExtra("threadId");

        threadId = Integer.parseInt(thread);

        write_message = (EditText) findViewById(R.id.write_a_message);
        post_message_button = (Button) findViewById(R.id.send_message_button);

        final ListView convoListView = (ListView) this.findViewById(R.id.conversationListView);

        final ArrayList<ConversationItem> convoItems = this.GetItems(threadId);

        final ConversionAdapter convoAdapter = new ConversionAdapter
                (this, R.layout.conversation_list_item, convoItems);

        convoListView.setAdapter(convoAdapter);

        post_message_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                convoItems.add(new ConversationItem(1, 1, "Bob Doe", DateTime.now(), write_message.getText().toString()));

                convoAdapter.notifyDataSetChanged();


                if (v.getId() == R.id.send_message_button);
                write_message.setText("");
            }
        });
        convoListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(ConversationView.this, "Clicked", Toast.LENGTH_LONG)
                        .show();
            }
        });
        convoListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {

                final int checkedCount = convoListView.getCheckedItemCount();
                mode.setTitle(checkedCount + " Message selected");
                convoAdapter.toggleSelection(position);
            }


            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.delete:
                        // Calls getSelectedIds method from ListViewAdapter Class
                        SparseBooleanArray selected = convoAdapter
                                .getSelectedIds();
                        // Captures all selected ids with a loop
                        for (int i = (selected.size() - 1); i >= 0; i--) {
                            if (selected.valueAt(i)) {
                                ConversationItem selecteditem = convoAdapter
                                        .getItem(selected.keyAt(i));
                                // Remove selected items following the ids
                                convoAdapter.remove(selecteditem);
                            }
                        }
                        // CAB
                        mode.finish();
                        return true;
                    default:
                        return false;

                }
            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                mode.getMenuInflater().inflate(R.menu.activity_main, menu);
                return true;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                // TODO Auto-generated method stub
                convoAdapter.removeSelection();
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                // TODO Auto-generated method stub
                return false;
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_conversation_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
          int id = item.getItemId();
     if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public ArrayList<ConversationItem> GetItems(Integer threadId) {
        ArrayList<ConversationItem> convos = new ArrayList<>();
        convos.add(new ConversationItem(1, 1, "Bob Smith", DateTime.now(), "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a mauris tincidunt, vehicula elit at, porta sem. Sed aliquam nisi fringilla, congue libero at, dignissim velit. Maecenas et libero sagittis urna tristique rhoncus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec lacinia nunc sed faucibus suscipit. Curabitur."));
        convos.add(new ConversationItem(1, 2, "Bob Smith", DateTime.now(), "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a mauris tincidunt, vehicula elit at, porta sem. Sed aliquam nisi fringilla, congue libero at, dignissim velit. Maecenas et libero sagittis urna tristique rhoncus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec lacinia nunc sed faucibus suscipit. Curabitur."));

           ArrayList<ConversationItem> returnItems = new ArrayList<>();

        for (int i = 0; i < convos.size(); i++) {
            if (convos.get(i).ThreadId.equals(threadId)) {
                returnItems.add(convos.get(i));
            }
        }

        return returnItems;
    }


    public class ConversionAdapter extends ArrayAdapter<ConversationItem> {

        LayoutInflater inflater;
        private SparseBooleanArray mSelectedItemsIds;
        private final ArrayList<ConversationItem> items;
        private int currentPage = 0;

        public ConversionAdapter(Context context, int resourceId, ArrayList<ConversationItem> convoItems) {
            super(context, resourceId, convoItems);
            mSelectedItemsIds = new SparseBooleanArray();
            this.context = context;
            this.items = convoItems;
            inflater = LayoutInflater.from(context);

        }


        public View getView(int position, View convertView, ViewGroup parent) {
            ListView list = (ListView) parent;


            {
                LayoutInflater inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


                convertView = getLayoutInflater().inflate
                        (R.layout.conversation_list_item, parent, false);

                //Username
                TextView username = (TextView) convertView
                        .findViewById(R.id.conversation_username);
                username.setText(items.get(position).convoUsername);

                //Date Time
                TextView dateTime = (TextView) convertView
                        .findViewById(R.id.conversation_date);
                dateTime.setText(items.get(position).DateTimeStamp.toString());

                //Message
                TextView message = (TextView) convertView
                        .findViewById(R.id.conversation_message);
                message.setText(items.get(position).Message);

            }

            return convertView;
        }

        @Override
        public void remove(ConversationItem object) {
            items.remove(object);
            notifyDataSetChanged();
        }

        public ArrayList<ConversationItem> getConversationItems() {
            return items;
        }

        public void toggleSelection(int position) {
            selectView(position, !mSelectedItemsIds.get(position));
        }

        public void removeSelection() {
            mSelectedItemsIds = new SparseBooleanArray();
            notifyDataSetChanged();
        }

        public void selectView(int position, boolean value) {
            if (value)
                mSelectedItemsIds.put(position, value);
            else
                mSelectedItemsIds.delete(position);
            notifyDataSetChanged();
        }

        public int getSelectedCount() {
            return mSelectedItemsIds.size();
        }

        public SparseBooleanArray getSelectedIds() {
            return mSelectedItemsIds;
        }
    }


}

1 个答案:

答案 0 :(得分:0)

您可以在EditText中添加addTextChangedListener:

write_message.addTextChangedListener(new TextWatcher() {

    public void onTextChanged(CharSequence c, int start, int before, int count) {

    /* store text entered */

    /* when the user presses the button */



    }

    public void beforeTextChanged(CharSequence c, int start, int count, int after) {

    /* probably blank */

    }

    public void afterTextChanged(Editable c) {

    /* probably blank */

    }

});