Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

android - how to get current week days in calender

I'm using this examplecode http://www.androidhub4you.com/2012/10/custom-calendar-in-android.html I want to show only currrent month days in gridview. I describle my problem below. Help me please. I just wana show current week days.

Suppose today date is 21 july and Wednesday grid show single row with this values

 Sun  Mon tues  Wed  Thurs  Fri  Sat
 18    19   20  (21)  22    23    24

but my code will only display this value

 Sun  Mon tues  Wed  Thurs  Fri  Sat
 1    2   3      4     5     6    7

I change this code form example code

 // Current Month Days
 for (int i = 1; i <= daysInMonth; i++) {
 Log.d(currentMonthName, String.valueOf(i) + " "
  + getMonthAsString(currentMonth) + " " + yy);
if (i == getCurrentDayOfMonth()) {
 list.add(String.valueOf(i) + "-BLUE" + "-"
   + getMonthAsString(currentMonth) + "-" + yy);
 } else {
 list.add(String.valueOf(i) + "-WHITE" + "-"
   + getMonthAsString(currentMonth) + "-" + yy);
 }

with this code

                   // Current Month Days
        for (int i = 1; i <= currentWeekDay; i++) {
            Log.d(currentMonthName, String.valueOf(i) + " "
                    + getMonthAsString(currentMonth) + " " + 
  yy);
            if (i == getCurrentDayOfMonth()) {
                list.add(String.valueOf(i) + "-BLUE" + "-"
                        + getMonthAsString(currentMonth) + 
     "-" + yy);
            } else {
                list.add(String.valueOf(i) + "-WHITE" + "-"
                        + getMonthAsString(currentMonth) + 
 "-" + yy);
            }







         ///////    full source code is below////////////






           public class MyCalendarActivity extends Activity implements  
   OnClickListener   {
private static final String tag = "MyCalendarActivity";

private TextView currentMonth;
private Button selectedDayMonthYearButton;
private ImageView prevMonth;
private ImageView nextMonth;


 private GridView calendarView;
private GridCellAdapter adapter;
private Calendar _calendar;
@SuppressLint("NewApi")
private int month, year;
@SuppressWarnings("unused")
@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
private final DateFormat dateFormatter = new DateFormat();
private static final String dateTemplate = "MMMM yyyy";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_calendar_view);

    _calendar = Calendar.getInstance(Locale.getDefault());
    month = _calendar.get(Calendar.MONTH) + 1;
    year = _calendar.get(Calendar.YEAR);
    Log.d(tag, "Calendar Instance:= " + "Month: " + month + " " + "Year: "
            + year);

    selectedDayMonthYearButton = (Button) this
            .findViewById(R.id.selectedDayMonthYear);
    selectedDayMonthYearButton.setText("Selected: ");

    prevMonth = (ImageView) this.findViewById(R.id.prevMonth);
    prevMonth.setOnClickListener(this);

    currentMonth = (TextView) this.findViewById(R.id.currentMonth);
    currentMonth.setText(DateFormat.format(dateTemplate,
            _calendar.getTime()));

    nextMonth = (ImageView) this.findViewById(R.id.nextMonth);
    nextMonth.setOnClickListener(this);
    calendarView = (GridView) this.findViewById(R.id.calendar);



    adapter = new GridCellAdapter(getApplicationContext(),
            R.id.calendar_day_gridcell, month, year);
    adapter.notifyDataSetChanged();
    calendarView.setAdapter(adapter);
}

/**
 * 
 * @param month
 * @param year
 */
private void setGridCellAdapterToDate(int month, int year) {
    adapter = new GridCellAdapter(getApplicationContext(),
            R.id.calendar_day_gridcell, month, year);
    _calendar.set(year, month - 1, _calendar.get(Calendar.DAY_OF_WEEK));
    currentMonth.setText(DateFormat.format(dateTemplate,
            _calendar.getTime()));
    adapter.notifyDataSetChanged();
    calendarView.setAdapter(adapter);
}

@Override
public void onClick(View v) {
    if (v == prevMonth) {
        if (month <= 1) {
            month = 12;
            year--;
        } else {
            month--;
        }
        Log.d(tag, "Setting Prev Month in GridCellAdapter: " + "Month: "
                + month + " Year: " + year);
        setGridCellAdapterToDate(month, year);
    }
    if (v == nextMonth) {
        if (month > 11) {
            month = 1;
            year++;
        } else {
            month++;
        }
        Log.d(tag, "Setting Next Month in GridCellAdapter: " + "Month: "
                + month + " Year: " + year);
        setGridCellAdapterToDate(month, year);
    }

}

@Override
public void onDestroy() {
    Log.d(tag, "Destroying View ...");
    super.onDestroy();
}

// Inner Class
public class GridCellAdapter extends BaseAdapter implements OnClickListener {
    private static final String tag = "GridCellAdapter";
    private final Context _context;

    private final List<String> list;
    private static final int DAY_OFFSET = 1;
    private final String[] weekdays = new String[] { "Sun", "Mon", "Tue",
            "Wed", "Thu", "Fri", "Sat" };
    private final String[] months = { "January", "February", "March",
            "April", "May", "June", "July", "August", "September",
            "October", "November", "December" };
    private final int[] daysOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
            31, 30, 31 };
    private int daysInMonth;
    private int currentDayOfMonth;
    private int currentWeekDay;
    private Button gridcell;
    private TextView num_events_per_day;
    private final HashMap<String, Integer> eventsPerMonthMap;
    private final SimpleDateFormat dateFormatter = new SimpleDateFormat(
            "dd-MMM-yyyy");

    // Days in Current Month
    public GridCellAdapter(Context context, int textViewResourceId,
            int month, int year) {
        super();
        this._context = context;
        this.list = new ArrayList<String>();
        Log.d(tag, "==> Passed in Date FOR Month: " + month + " "
                + "Year: " + year);
        Calendar calendar = Calendar.getInstance();
        setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
        setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
        Log.d(tag, "New Calendar:= " + calendar.getTime().toString());
        Log.d(tag, "CurrentDayOfWeek :" + getCurrentWeekDay());
        Log.d(tag, "CurrentDayOfMonth :" + getCurrentDayOfMonth());

        // Print Month
        printMonth(month, year);

        // Find Number of Events
        eventsPerMonthMap = findNumberOfEventsPerMonth(year, month);
    }

    private String getMonthAsString(int i) {
        return months[i];
    }

    private String getWeekDayAsString(int i) {
        return weekdays[i];
    }

    private int getNumberOfDaysOfMonth(int i) {
        return daysOfMonth[i];
    }

    public String getItem(int position) {
        return list.get(position);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    /**
     * Prints Month
     * 
     * @param mm
     * @param yy
     */
    private void printMonth(int mm, int yy) {
        Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy: " + yy);
        int trailingSpaces = 0;
        int daysInPrevMonth = 0;
        int prevMonth = 0;
        int prevYear = 0;
        int nextMonth = 0;
        int nextYear = 0;

        int currentMonth = mm - 1;
        String currentMonthName = getMonthAsString(currentMonth);
        daysInMonth = getNumberOfDaysOfMonth(currentMonth);

        Log.d(tag, "Current Month: " + " " + currentMonthName + " having "
                + daysInMonth + " days.");

        GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 1);
        Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());

        if (currentMonth == 11) {
            prevMonth = currentMonth - 1;
            daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
            nextMonth = 0;
            prevYear = yy;
            nextYear = yy + 1;
            Log.d(tag, "*->PrevYear: " + prevYear + " PrevMonth:"
                    + prevMonth + " NextMonth: " + nextMonth
                    + " NextYear: " + nextYear);
        } else if (currentMonth == 0) {
            prevMonth = 11;
            prevYear = yy - 1;
            nextYear = yy;
            daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
            nextMonth = 1;
            Log.d(tag, "**--> PrevYear: " + prevYear + " PrevMonth:"
                    + prevMonth + " NextMonth: " + nextMonth
                    + " NextYear: " + nextYear);
        } else {
            prevMonth = currentMonth - 1;
            nextMonth = currentMonth + 1;
            nextYear = yy;
            prevYear = yy;
            daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
            Log.d(tag, "***---> PrevYear: " + prevYear + " PrevMonth:"
                    + prevMonth + " NextMonth: " + nextMonth
                    + " NextYear: " + nextYear);
        }

        int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
        trailingSpaces = currentWeekDay;

        Log.d(tag, "Week Day:" + currentWeekDay + " is "
                + getWeekDayAsString(currentWeekDay));
        Log.d(tag, "No. Trailing space to Add: " + trailingSpaces);
        Log.d(tag, "No. of Days in Previous Month: " + daysInPrevMonth);

        if (cal.isLeapYear(cal.get(Calendar.YEAR)))
            if (mm == 2)
                ++daysInMonth;
            else if (mm == 3)
                ++daysInPrevMonth;

        // Trailing Month days
        for (int i = 0; i < trailingSpaces; i++) {
            Log.d(tag,
                    "PREV MONTH:= "
                            + prevMonth
                            + " => "
                            +    
 getMonthAsString(prevMonth)
                            + " "
                            + 
  String.valueOf((daysInPrevMonth
                                    - 
 trailingSpaces + DAY_OFFSET)
                                    + i));
            list.add(String
                    .valueOf((daysInPrevMonth - trailingSpaces 
   + DAY_OFFSET)
                            + i)
                    + "-GREY"
                    + "-"
                    + getMonthAsString(prevMonth)
                    + "-"
                    + prevYear);
        }

        // Current Month Days
        for (int i = 1; i <= currentWeekDay; i++) {
            Log.d(currentMonthName, String.valueOf(i) + " "
                    + getMonthAsString(currentMonth) + " " + 
yy);
            if (i == getCurrentDayOfMonth()) {
                list.add(String.valueOf(i) + "-BLUE" + "-"
                        + getMonthAsString(currentMonth) + 
  "-" + yy);
            } else {
                list.add(String.valueOf(i) + "-WHITE" + "-"
                        + getMonthAsString(currentMonth) + 
     "-" + yy);
            }
        }

        // Leading Month days
        for (int i = 0; i < list.size() % 7; i++) {
            Log.d(tag, "NEXT MONTH:= " + getMonthAsString(nextMonth));
            list.add(String.valueOf(i + 1) + "-GREY" + "-"
                    + getMonthAsString(nextMonth) + "-" +  
   nextYear);
        }
    }

    /**
     * NOTE: YOU NEED TO IMPLEMENT THIS PART Given the YEAR, MONTH, retrieve
     * ALL entries from a SQLite database for that month. Iterate o

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I hope this is what you want.

  1. Rename your printMonth() to printMonth_old ()
  2. Copy and paste the printMonth code below
  3. Modify the getView() method with one line.
  4. Create the 3 variables in the Activity and modify the onCreate to initialize them
  5. Try it

There are some changes you need to do, for eaxmple when click the Next Button advance one week and the when click Prev. Button go back one week.

1) Copy and paste this code, after renaming your actual printMonth

    private void printMonth(int mm, int yy)
    {
        Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy: " + yy);
        int trailingSpaces = 0;
        int daysInPrevMonth = 0;

        int currentMonth = mm - 1;
        String currentMonthName = getMonthAsString(currentMonth);
        daysInMonth = getNumberOfDaysOfMonth(currentMonth);

        Log.d(tag, "Current Month: " + " " + currentMonthName + " having " + daysInMonth + " days.");

        GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, getCurrentDayOfMonth());
        Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());

        int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
        trailingSpaces = currentWeekDay;

        Log.d(tag, "Week Day:" + currentWeekDay + " is " + getWeekDayAsString(currentWeekDay));
        Log.d(tag, "No. Trailing space to Add: " + trailingSpaces);
        Log.d(tag, "No. of Days in Previous Month: " + daysInPrevMonth);

        if (cal.isLeapYear(cal.get(Calendar.YEAR)))
            if (mm == 2) ++daysInMonth;
            else if (mm == 3)
                ++daysInPrevMonth;

        // move at the begging of the week
        int i = getCurrentDayOfMonth();
        int j = currentWeekDay;
        while (i > 1 && j > 0)
        {
            i--;
            j--;
        }
        // print the week, starting at Sunday
        for (j = 0; i <= daysInMonth && j < 7; i++, j++)
        {
            Log.d(currentMonthName, String.valueOf(i) + " " + getMonthAsString(currentMonth) + " " + yy);
            // If it is the current date, printing in BLUE (Orange)
            if (i == actualDay && mm == actualMonth && yy == actualYear)
            {
                list.add(String.valueOf(i) + "-BLUE" + "-" + getMonthAsString(currentMonth) + "-" + yy);
            }
            else
            {
                list.add(String.valueOf(i) + "-WHITE" + "-" + getMonthAsString(currentMonth) + "-" + yy);
            }
        }
    }

2) Change the getView method, only add one line:

if (day_color[1].equals("BLUE"))
{
    // Add only the following line
    gridcell.setText("(" + theday + ")");
    gridcell.setTextColor(getResources().getColor(R.color.orrange));
}

3) On the Activity add this line:

public class MyCalendarActivity extends Activity implements OnClickListener
{
    ....
    private int month, year;
    // add this line below
    private int actualYear, actualMonth, actualDay;

And on the onCreate() add these lines as well:

public void onCreate(Bundle savedInstanceState)
{
  ....

  month = _calendar.get(Calendar.MONTH) + 1;
  year = _calendar.get(Calendar.YEAR);
  // Add these 3 lines          
  actualYear = year;
  actualMonth = month;
  actualDay = _calendar.get(Calendar.DAY_OF_MONTH);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...