簡體   English   中英

用GregorianCalendar日期對象填充ArrayList

[英]Populating ArrayList with GregorianCalendar date objects

我試圖用GregorianCalendar對象填充ArrayList,以便我可以進一步將其附加到listview適配器。 此處顯示的快照是我想要實現的.....我希望日期對象的列表成為組listview,以便可以將其與特定日期下的事件進行比較(即事件將是子listview)。 到目前為止,我已經編寫了一些代碼,但是它沒有像快照中那樣用日期填充arraylist,而是僅添加了當前日期(即僅添加了一個元素)。 提前致謝。

這是我的代碼

public class EventFragment extends Fragment{

List<GregorianCalendar> dates = new ArrayList<GregorianCalendar>();
List<Events> events = new ArrayList<Events>();

SimpleDateFormat dateFormat;
GregorianCalendar calendar_date;

public EventFragment(){ }


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_events, container, false);
    return rootView;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    listView = (ListView) getView().findViewById(R.id.list);

    dateFormat =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    calendar_date = new GregorianCalendar();
    dates.add(calendar_date);

    for(int i = 0; i < dates.size(); i++){
        Log.e("Date", ""+calendar_date.get(i));
    }       
}
}

這實際上比我想像的要復雜。 這並不困難,但是會花費更多的代碼。

我可以舉一個生成日期范圍的簡單示例,如下所示。 為簡單起見,例如,我只做一個月-2015年1月...

Calendar startDate = new GregorianCalendar();

// Set the start date to 1st Jan 2015 and time to 00:00:00 using
// set(int year, int month, int day, int hourOfDay, int minute, int second)
// NOTE: the month field is in the range 0-11 with January being 0
startDate.set(2015, 0, 1, 0, 0, 0);

// Clone the start date and add one month to set the end date to
// 1st February 2015 00:00:00
Calendar endDate = startDate.clone();
endDate.add(Calendar.MONTH, 1); // This adds 1 month

// Step through each day from startDate to endDate (not including endDate itself)
while (startDate.before(endDate)) {

    // Do whatever you need to do here to get the date string from startDate
    // using SimpleDateFormat for example. For logging purposes you can
    // use the next line...
    Log.e("Date", startDate.toString());

    // Now increment the day as follows...
    startDate.add(Calendar.DAY_OF_MONTH, 1);
}

保存事件數據時,您需要做更多的工作,我建議您使用SQLite DB。 然后,我建議您將日期列表更改為僅保留格式化的日期字符串,而不要使用GregorianCalendar實例。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM