每个列表项都包含当前日期和时间

时间:2015-10-14 05:55:43

标签: android android-studio

这是我的 MainActivity.class 代码,用于向列表项添加值。 我想在singleItem中添加当前日期和时间的每个项目。

问题:我的代码会在新条目中提供当前日期和时间。 我怎么解决呢?

 h_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String message = h_text.getText().toString();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
                String currentDateandTime = sdf.format(new Date());

                if (message.trim() != "" && currentDateandTime.trim()!="") {
                    list.add(0, message);
                    list.add(0,currentDateandTime);

                    adapter.notifyDataSetChanged();
                    h_text.setText("");


                }
            }
        });
    }

3 个答案:

答案 0 :(得分:0)

如果您使用自定义列表视图,viewholder将解决问题。

答案 1 :(得分:0)

如果您只想要单个项目,则不能使用这样的添加:

list.add(0,currentDateandTime);

将第一个元素移动到第二个位置,然后在第一个位置添加新元素。 因此,无论何时使用该行,它都会在列表中添加一个项目。

您可以尝试list.remove(0)它将删除第一个位置的项目,然后使用list.add(0,currentDateandTime)

答案 2 :(得分:0)

您需要的是HashMap或列表列表。

如果您不确定密钥的唯一性作为密钥,值对格式的hashMap存储值,我建议您使用列表列表。

List<List<String>> list = new ArrayList<List<String>>();

List<String> yourdataList = new ArrayList<String>();
yourdataList.add(message);
yourdataList.add(currentDateandTime);

list.add(yourdataList);