如何将时间戳添加到列表视图?

Posted

技术标签:

【中文标题】如何将时间戳添加到列表视图?【英文标题】:how to add a time stamp to a List View? 【发布时间】:2016-12-16 09:06:37 【问题描述】:

我想在listView 中添加timeStamp,以便在此代码中创建项目时向您显示。有什么办法吗,我可以这样做。如果有人知道如何做到这一点,请告诉我。 to_do_item_layout

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_
android:layout_>

<CheckBox
    android:id="@+id/checkBox"
    android:layout_
    android:layout_ />

<TextView
    android:id="@+id/item"
    android:layout_
    android:layout_
    android:layout_weight="1"
    android:textSize="20sp"/>

<ImageButton
    android:id="@+id/delete_Button"
    android:src="@drawable/delete_item_button"
    android:background="@android:color/transparent"
    android:layout_
    android:layout_
    android:contentDescription="@string/delete_item"/>
<TextView
    android:layout_
    android:layout_
    android:id="@+id/timeStamp"
    />

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper 
public static final String DATABASE_NAME = "todo.db";
public static final int DATABASE_VERSION = 1;
public static final String ITEMS_TABLE = "items";

private static DatabaseHelper instance = null;

public static DatabaseHelper getInstance(Context context) 

    if(instance == null) 
        instance = new DatabaseHelper(context);
    
    return instance;


private DatabaseHelper(Context context) 
    super(context, DATABASE_NAME, null, DATABASE_VERSION);


@Override
public void onCreate(SQLiteDatabase db) 

    String createQuery = "CREATE TABLE " + ITEMS_TABLE + " (" +
            "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
            "description TEXT NOT NULL, " +
            "completed INTEGER NOT NULL DEFAULT 0)"+
            "timeStamp INTEGER NOT NULL)";
    db.execSQL(createQuery);


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)       

 

 

该按钮工作正常,但不会永久删除>

MainActivity.java

 public class MainActivity extends AppCompatActivity 

private static final String LOG_TAG = "ToDoApp";

private ToDoListManager listManager;
private ToDoItemAdapter adapter;

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

    ListView todoList = (ListView) findViewById(R.id.todo_list);

    listManager = new ToDoListManager(getApplicationContext());

    adapter = new ToDoItemAdapter(
            this,
            listManager.getList()
    );

    todoList.setAdapter(adapter);

    ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
    addButton.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            onAddButtonClick();
        
    );


@Override
protected void onPause() 
    super.onPause();


private void onAddButtonClick() 
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.add_item);

    final EditText input = new EditText(this);
    input.setInputType(InputType.TYPE_CLASS_TEXT);
    builder.setView(input);

    builder.setPositiveButton(
            R.string.ok,
            new DialogInterface.OnClickListener() 

                @Override
                public void onClick(DialogInterface dialog, int which) 
                    ToDoItem item = new ToDoItem(
                            input.getText().toString(),
                            false
                    );
                    listManager.addItem(item);
                    adapter.swapItems(listManager.getList());
                
            );

    builder.setNegativeButton(
            R.string.cancel,
            new DialogInterface.OnClickListener() 

                @Override
                public void onClick(DialogInterface dialog, int which) 
                    dialog.cancel();
                
            );

    builder.show();


private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> 


    private Context context;
    private List<ToDoItem> items;
    private LayoutInflater inflater;

    public ToDoItemAdapter(
            Context context,
            List<ToDoItem> items
    ) 
        super(context, -1, items);

        this.context = context;
        this.items = items;
        this.inflater = LayoutInflater.from(context);
    

    public void swapItems(List<ToDoItem> items) 
        this.items = items;
        notifyDataSetChanged();
    


    @Override
    public int getCount() 
        return items.size();
    



    @Override
    public View getView(final int position, View convertView, ViewGroup parent) 



        final ItemViewHolder holder;



        if(convertView == null) 

            convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);


            holder = new ItemViewHolder();
            holder.itemDescription = (TextView) convertView.findViewById(R.id.item);
            holder.itemState = (CheckBox) convertView.findViewById(R.id.checkBox);
            holder.itemTimeStamp = (TextView) convertView.findViewById(R.id.timeStamp);
            holder.itemTimeStamp.setText(getPassedTimeForCreation(item.getTimeStamp()));



            convertView.setTag(holder);
        else 
            holder = (ItemViewHolder) convertView.getTag();
        


       holder.itemDescription.setText(items.get(position).getDescription());
        holder.itemState.setChecked(items.get(position).isComplete());


        holder.itemState.setTag(items.get(position));

        convertView.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                ToDoItem item = (ToDoItem) holder.itemState.getTag();
                item.toggleComplete();
                listManager.updateItem(item);
                notifyDataSetChanged();
            
        );
        ImageButton deleteButton = (ImageButton) convertView.findViewById(R.id.delete_Button);
        deleteButton.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                long itemId = items.get(position).getId();
                items.remove(items.get(position));
                listManager.deleteItem(itemId);
                notifyDataSetChanged();
            
        );

        holder.itemState.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                ToDoItem item = (ToDoItem) holder.itemState.getTag();
                item.toggleComplete();
                listManager.updateItem(item);
                notifyDataSetChanged();

            
        );

        return convertView;
    



public static class ItemViewHolder
    public TextView itemDescription;
    public CheckBox itemState;

String getPassedTimeFromCreation(Long timeStamp)

    Calendar now = Calendar.getInstance();
    Long differece = now.getTimeInMillis() - timeStamp;

    if (differece < (5 * 60 * 1000))  // (5 minute in milliseconds)
        return "5 min ago";
    
    else if(differece < (2 * 24 * 60 * 60 * 1000)) // (2 days in millisecond)
        return "2 days ago";
    else
        return "long time ago";
    



ToDoListManager.java

public class ToDoListManager 
private DatabaseHelper dbHelper;
public ToDoListManager(Context context) 
    dbHelper = DatabaseHelper.getInstance(context);


public List<ToDoItem> getList() 

    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(
            "SELECT * FROM " + DatabaseHelper.ITEMS_TABLE,
            null
    );

    List<ToDoItem> items = new ArrayList<>();

    if(cursor.moveToFirst()) 
        while(!cursor.isAfterLast()) 

            ToDoItem item = new ToDoItem(
                                           cursor.getString(cursor.getColumnIndex("description")),
             cursor.getInt(cursor.getColumnIndex("completed")) != 0,
             cursor.getLong(cursor.getColumnIndex("_id")),
             cursor.getLong(cursor.getColumnIndex("timeStamp"))
            );
            items.add(item);
            cursor.moveToNext();
        
    
    cursor.close();
    return items;


public void addItem(ToDoItem item) 

    ContentValues newItem = new ContentValues();
    newItem.put("description", item.getDescription());
    newItem.put("completed", item.isComplete());
    newItem.put("timeStamp", item.getTimeStamp());

    SQLiteDatabase db = dbHelper.getWritableDatabase();
    db.insert(DatabaseHelper.ITEMS_TABLE, null, newItem);




public void updateItem(ToDoItem item) 

    ContentValues editItem = new ContentValues();
    editItem.put("description", item.getDescription());
    editItem.put("completed", item.isComplete());
    newItem.put("timeStamp", item.getTimeStamp());


    SQLiteDatabase db = dbHelper.getWritableDatabase();

    String[] args = new String[]  String.valueOf(item.getId()) ;

    db.update(DatabaseHelper.ITEMS_TABLE, editItem, "_id=?", args);



public void deleteItem(long itemId) 

    SQLiteDatabase db = dbHelper.getWritableDatabase();
    db.delete(DatabaseHelper.ITEMS_TABLE, "_id = ?",
            new String[]  String.valueOf(itemId) );


ToDoItem.java

import java.util.Calendar;
public class ToDoItem 
private long timeStamp;
private String description;
private boolean isComplete;
private long id;


public ToDoItem(String description, boolean isComplete, long id, long timeStamp) 
    this.description = description;
    this.isComplete = isComplete;
    this.id = id;
    this.timeStamp = timeStamp;



public ToDoItem(String description, boolean isComplete, long id) 
    this.description = description;
    this.isComplete = isComplete;
    this.id = id;
    Calendar now = Calendar.getInstance();
    this.timeStamp = now.getTimeInMillis();




public String getDescription() 
    return description;


public boolean isComplete() 
    return isComplete;


public void toggleComplete() 
    isComplete = !isComplete;

public long getId() return id;

@Override
public String toString() 

    return getDescription();



MainActivity

Todo_list_manager

【问题讨论】:

我先有一个问题再回答。您只想显示项目数据创建的时间戳,还是想在列表视图中显示项目膨胀时间?您是否要在数据库中存储时间戳? 这是一个 todolist 应用程序,所以每次他们添加新的待办事项时,我都想看看我创建它的时间。 (例如 2 天前添加;5 分钟前添加)。 因此您需要在数据库中再添加一列来存储用户toDoItem 创建。为了以Added 2 days ago; Added 5 minutes ago 格式显示时间,您需要编写一个函数,将项目创建时间与操作系统当前时间进行比较并生成正确的字符串 我正在写答案,需要一些时间,请稍候! 关于问题感谢您的帮助。 【参考方案1】:

我认为这个修改对你有帮助,我只是写了主要部分,你需要自己应用更改。祝你好运!

DatabaseHelper.java

@Override
public void onCreate(SQLiteDatabase db) 

    String createQuery = "CREATE TABLE " + ITEMS_TABLE + " (" +
            "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
            "description TEXT NOT NULL, " +
            "completed INTEGER NOT NULL DEFAULT 0," + 
            "timeStamp INTEGER NOT NULL)";
    db.execSQL(createQuery);

ToDoItem.java

public class ToDoItem 
    private Long timeStamp;
    private String description;
    private boolean isComplete;
    private long id;

    // I just added two getter and setter methods
    public void setTimeStamp(Long timeStamp)
        this.timeStamp = timeStamp;
    

    public Long getTimeStamp()
        return timeStamp;
    

    public ToDoItem(String description,boolean isComplete,long id, Long timeStamp) 
        this.description = description;
        this.isComplete = isComplete;
        this.id = id;
        this.timeStamp = timeStamp;
    

    public ToDoItem(String description,boolean isComplete,long id) 
        this.description = description;
        this.isComplete = isComplete;
        this.id = id;
        Calendar now = Calendar.getInstance();
        this.timeStamp = now.getTimeInMillis();
    


ToDoListManager.java

public List<ToDoItem> getList() 
    ...
    ToDoItem item = new ToDoItem(
                    cursor.getString(cursor.getColumnIndex("description")),
                    cursor.getInt(cursor.getColumnIndex("completed")) != 0,
                    cursor.getLong(cursor.getColumnIndex("_id")),
                    cursor.getLong(cursor.getColumnIndex("timeStamp"))
            );
    ...


public void addItem(ToDoItem item) 
    ...
    // add this line
    newItem.put("timeStamp", item.getTimeStamp());
    ...


public void updateItem(ToDoItem item) 
    ...
    // add this line
    editItem.put("timeStamp", item.getTimeStamp());
    ...

ToDoItemAdapter

我假设您将 TextView timeStamp 添加到您的 to_do_item_layout 和您的 ItemViewHolder 类中

ItemViewHolder

public static class ItemViewHolder
    public TextView itemDescription;
    public CheckBox itemState;
    public TextView itemTimeStamp;
   

getView 添加这一行

holder.itemTimeStamp = (TextView) convertView.findViewById(R.id.timeStamp);
holder.itemTimeStamp.setText(getPassedTimeForCreation(item.getTimeStamp()));

getPassedTimeForCreation(Long timeStamp)

String getPassedTimeFromCreation(Long timeStamp)
        Calendar now = Calendar.getInstance();
        Long differece = now.getTimeInMillis() - timeStamp;

        if (differece < (5 * 60 * 1000))  // (5 minute in milliseconds)
            return "5 min ago";
        
        else if(differece < (2 * 24 * 60 * 60 * 1000)) // (2 days in millisecond)
            return "2 days ago";
        else
            return "long time ago";
        
    

在 MainActivity 类中添加 getPassedTimeForCreation 函数,而不是在 MainActivity 的函数体内!!!

@Override
protected void onCreate(Bundle savedInstanceState) 
    `...`


@Override
protected void onPause() 
    `...`


private void onAddButtonClick() 
    `...`


private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> 
    `...`


public static class ItemViewHolder
    `...`


/**
 * this is the place that you must put the function!
 */
String getPassedTimeFromCreation(Long timeStamp)
    `...`

【讨论】:

getPassedTimeForCreation函数目前精度低,例如如果一个项目是在6分钟前创建的,则返回2 days ago,如果您需要更高的精度,您需要检查更多if条件 我在哪里放 getPassedTimeForCreation(Long timeStamp) 你可以把函数放在MainActivity.java 我在最后的评论中无法弄清楚你的问题 抱歉回复晚了。我的意思是代码不适用于 ToDoListManager.java 它说无法解析方法。

以上是关于如何将时间戳添加到列表视图?的主要内容,如果未能解决你的问题,请参考以下文章

如何从列表视图按钮单击将多个数据添加到数组列表?

如何使用自定义适配器将整数添加到列表视图

Android Studio:如何将列表视图中的项目添加到列表视图 onClick

如何在列表视图的滚动中添加更多项目?

将列表添加到视图而不更改视图

如何将页脚视图添加到 SwiftUI 中的列表?