2014-12-04 79 views
0

我正在尝试使用GregorianCalendar对象填充ArrayList,以便我可以进一步将其附加到列表视图适配器。显示的快照here是我想要实现.....我希望日期对象的列表成为组列表视图,以便它可以与特定日子下的事件(即事件将是子列表视图)进行比较。到目前为止,我已经编写了一些代码,但它并没有像snapshot那样用日期填充数组列表,而是仅添加当前日期(即只有一个元素)。提前致谢。使用GregorianCalendar日期对象填充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)); 
    }  
} 
} 
+0

您只添加到列表一次('dates.add(calendar_date);')。 – GriffeyDog 2014-12-04 21:10:43

+0

@GriffeyDog,我将(dates.add(calendar_date);)移到循环中,它仍然返回与今天相关的日期 – mish 2014-12-04 21:18:24

+0

@mish:'GregorianCalendar'只能表示一个日期/时间。它不是像日历应用程序那样具有多个日期的“完整”日历。 – Squonk 2014-12-04 21:22:03

回答

0

这实际上比我想你实现更多复杂。这并不困难,但需要更多的代码。

我可以举一个简单的例子来生成如下的日期范围。为了简单起见,我就做一月份 - 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数据库。然后我会建议你改变你的日期列表来简单地保存格式化的日期字符串而不是GregorianCalendar的实例。

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

谢谢你的回答.....它启发了我更多。请你可以向我推荐任何有帮助的源代码。 – mish 2014-12-04 23:57:12

+0

@mish:我只能推荐你在Google上搜索Google日历应用示例 - 我确定那里肯定有不少。 – Squonk 2014-12-05 00:14:53