This is my code my problem is this . in calendar view pager adapter i am 5000 page but offScreenPage limit is 1 and I have 3 pages in on time but view pager is not smoth scroll and has bad performance. when I remove this line from Calendar fragment view pager smooth scroll fine. but I dont know what is the problem.
gregorianCal = new GregorianCalendar(persianCal);
IslamicCalendar islamicCal = new IslamicCalendar(persianCal);
///////////////////////////////////////////////
for (int i = 0; i < persianCal.getNumberOfDaysInMonth(); i++) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.nameOFDay = persianCal.getWeekDay();
//////set month names/////////////
dateCalendar.shamsiMonthName = persianCal.getMonthName();
dateCalendar.hejriMonthName = islamicCal.getMonthName();
dateCalendar.gregorianMonthName = gregorianCal.getMonthName();
//////set persian calendar/////
dateCalendar.shamsiDayNumber = persianCal.getDay();
dateCalendar.shamsiMonthNumber = persianCal.getMonth();
dateCalendar.shamsiYearNumber = persianCal.getYear();
//////set islamic calendar/////
dateCalendar.hejriDayNumber = islamicCal.getDay();
dateCalendar.hejriMonthNumber = islamicCal.getMonth();
dateCalendar.hejriYearNumber = islamicCal.getYear();
//////set gregorian calendar/////
dateCalendar.gregorianDayNumber = gregorianCal.getDay();
dateCalendar.gregorianMonthNumber = gregorianCal.getMonth();
dateCalendar.gregorianYearNumber = gregorianCal.getYear();
///////select current day of Month
if (persianCal.getDay() == currentPersianCal.getDay() && persianCal.getMonth() == currentPersianCal.getMonth() && persianCal.getYear() == currentPersianCal.getYear()) {
dateCalendar.isCurrentDay = true;
dateCalendar.isDaySelected = true;
}
///////add days of current month//////
dateCalendarList.add(dateCalendar);
if (i < persianCal.getNumberOfDaysInMonth() - 1) {
persianCal.nextDay();
gregorianCal.nextDay();
islamicCal.nextDay();
}
}
I search a lot of similar subject of viewPager but I not found soultion for it.
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import com.example.moein.mycalendar.R;
import com.example.moein.mycalendar.myCalendar_adapter.GridAdapter1;
import com.example.moein.mycalendar.myCalendar_library.date.GregorianCalendar;
import com.example.moein.mycalendar.myCalendar_library.date.IslamicCalendar;
import com.example.moein.mycalendar.myCalendar_library.date.PersianCalendar;
import com.example.moein.mycalendar.myCalendar_library.util.Operations;
import com.example.moein.mycalendar.myCalendar_model.DateCalendar;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
/**
* Created by Moein on 9/16/2017.
*/
public class CalendarFragment extends Fragment {
private int year;
private int month;
private int day;
// newInstance constructor for creating fragment with arguments
public static CalendarFragment newInstance(int year, int month, int day) {
CalendarFragment calendarFragment = new CalendarFragment();
Bundle args = new Bundle();
args.putInt("year", year);
args.putInt("month", month);
args.putInt("day", day);
calendarFragment.setArguments(args);
return calendarFragment;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
year = getArguments().getInt("year");
month = getArguments().getInt("month");
day = getArguments().getInt("day");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_calendar, container, false);
TextView yearAndMonth = view.findViewById(R.id.yearAndMonth);
GridView gridView = view.findViewById(R.id.gridCalendar);
/////set timeZone Asia/Tehran and set current calendar///////////////////////////////
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
GregorianCalendar currentGregorianCal = new GregorianCalendar(calendar);
PersianCalendar currentPersianCal = new PersianCalendar(currentGregorianCal);
GregorianCalendar gregorianCal = new GregorianCalendar(year, month, day);
PersianCalendar persianCal = new PersianCalendar(gregorianCal);
/////////add weekDay names to the list of gridAdapter///////
String[] weekDays = getResources().getStringArray(R.array.weekDays);
List<DateCalendar> dateCalendarList = new ArrayList<>();
for (String weekDay : weekDays) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.nameOFDay = weekDay;
dateCalendarList.add(dateCalendar);
}
//set title of calendar/////////
yearAndMonth.setText(persianCal.getMonthName() + " " + Operations.toPersianNumber(String.valueOf(persianCal.getYear())));
///Back to the beginning of the month
persianCal.subtractDays(persianCal.getDay() - 1);
//////add empty days to the beginning of the month
int lengthOfEmptyDays = 0;
switch (persianCal.getWeekDay()) {
case "شنبه":
lengthOfEmptyDays = 0;
break;
case "یکشنبه":
lengthOfEmptyDays = 1;
break;
case "دوشنبه":
lengthOfEmptyDays = 2;
break;
case "سه\u200Cشنبه":
lengthOfEmptyDays = 3;
break;
case "چهارشنبه":
lengthOfEmptyDays = 4;
break;
case "پنج\u200Cشنبه":
lengthOfEmptyDays = 5;
break;
case "جمعه":
lengthOfEmptyDays = 6;
break;
}
for (int i = 0; i < lengthOfEmptyDays; i++) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.isEmpty = true;
dateCalendarList.add(dateCalendar);
}
gregorianCal = new GregorianCalendar(persianCal);
IslamicCalendar islamicCal = new IslamicCalendar(persianCal);
///////////////////////////////////////////////
for (int i = 0; i < persianCal.getNumberOfDaysInMonth(); i++) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.nameOFDay = persianCal.getWeekDay();
//////set month names/////////////
dateCalendar.shamsiMonthName = persianCal.getMonthName();
dateCalendar.hejriMonthName = islamicCal.getMonthName();
dateCalendar.gregorianMonthName = gregorianCal.getMonthName();
//////set persian calendar/////
dateCalendar.shamsiDayNumber = persianCal.getDay();
dateCalendar.shamsiMonthNumber = persianCal.getMonth();
dateCalendar.shamsiYearNumber = persianCal.getYear();
//////set islamic calendar/////
dateCalendar.hejriDayNumber = islamicCal.getDay();
dateCalendar.hejriMonthNumber = islamicCal.getMonth();
dateCalendar.hejriYearNumber = islamicCal.getYear();
//////set gregorian calendar/////
dateCalendar.gregorianDayNumber = gregorianCal.getDay();
dateCalendar.gregorianMonthNumber = gregorianCal.getMonth();
dateCalendar.gregorianYearNumber = gregorianCal.getYear();
///////select current day of Month
if (persianCal.getDay() == currentPersianCal.getDay() && persianCal.getMonth() == currentPersianCal.getMonth() && persianCal.getYear() == currentPersianCal.getYear()) {
dateCalendar.isCurrentDay = true;
dateCalendar.isDaySelected = true;
}
///////add days of current month//////
dateCalendarList.add(dateCalendar);
if (i < persianCal.getNumberOfDaysInMonth() - 1) {
persianCal.nextDay();
gregorianCal.nextDay();
islamicCal.nextDay();
}
}
gridView.setAdapter(new GridAdapter1(getActivity(), dateCalendarList));
return view;
}
}
public class CalendarViewPagerAdapter extends FragmentStatePagerAdapter{
private GregorianCalendar centerGregorianCalendar;
private GregorianCalendar nextGregorianCalendar;
private GregorianCalendar prevGregorianCalendar;
private final int MAX = 5000;
public CalendarViewPagerAdapter(FragmentManager fm, GregorianCalendar centerGregorianCalendar, GregorianCalendar nextGregorianCalendar, GregorianCalendar prevGregorianCalendar) {
super(fm);
this.centerGregorianCalendar = centerGregorianCalendar;
this.prevGregorianCalendar = prevGregorianCalendar;
this.nextGregorianCalendar = nextGregorianCalendar;
}
#Override
public Fragment getItem(int position) {
position = position % 3;
if (position == 0) {
return new CalendarFragment().newInstance(prevGregorianCalendar.getYear(), prevGregorianCalendar.getMonth(), prevGregorianCalendar.getDay());
} else if (position == 1) {
return new CalendarFragment().newInstance(centerGregorianCalendar.getYear(), centerGregorianCalendar.getMonth(), centerGregorianCalendar.getDay());
} else {
return new CalendarFragment().newInstance(nextGregorianCalendar.getYear(), nextGregorianCalendar.getMonth(), nextGregorianCalendar.getDay());
}
}
#Override
public int getCount() {
return MAX;
}
}
public class MainActivity extends AppCompatActivity {
private int[] CenterPage = {2500};
private CalendarViewPagerAdapter calendarViewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/////set timeZone Asia/Tehran///////////////////////////////
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
final GregorianCalendar gregorianCal = new GregorianCalendar(calendar);
final GregorianCalendar nextGregorianCal = new GregorianCalendar(calendar);
final GregorianCalendar prevGregorianCal = new GregorianCalendar(calendar);
if (gregorianCal.getMonth() == 12) {
nextGregorianCal.setMonth(1);
nextGregorianCal.setYear(nextGregorianCal.getYear() + 1);
} else {
nextGregorianCal.setMonth(nextGregorianCal.getMonth() + 1);
}
if (gregorianCal.getMonth() == 1) {
prevGregorianCal.setMonth(12);
prevGregorianCal.setYear(prevGregorianCal.getYear() - 1);
} else {
prevGregorianCal.setMonth(prevGregorianCal.getMonth() - 1);
}
final ViewPager calendarViewPager = findViewById(R.id.calendar_viewPager);
calendarViewPagerAdapter = new CalendarViewPagerAdapter(getSupportFragmentManager(), gregorianCal, nextGregorianCal, prevGregorianCal);
calendarViewPager.setAdapter(calendarViewPagerAdapter);
calendarViewPager.setOffscreenPageLimit(1);
calendarViewPager.setCurrentItem(2500);
calendarViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position < CenterPage[0]) {
switch (position % 3) {
case 0:
nextGregorianCal.set(prevGregorianCal);
if (nextGregorianCal.getMonth() == 1) {
nextGregorianCal.setMonth(12);
nextGregorianCal.setYear(nextGregorianCal.getYear() - 1);
} else {
nextGregorianCal.setMonth(nextGregorianCal.getMonth() - 1);
}
break;
case 1:
prevGregorianCal.set(gregorianCal);
if (prevGregorianCal.getMonth() == 1) {
prevGregorianCal.setMonth(12);
prevGregorianCal.setYear(prevGregorianCal.getYear() - 1);
} else {
prevGregorianCal.setMonth(prevGregorianCal.getMonth() - 1);
}
break;
case 2:
gregorianCal.set(nextGregorianCal);
if (gregorianCal.getMonth() == 1) {
gregorianCal.setMonth(12);
gregorianCal.setYear(gregorianCal.getYear() - 1);
} else {
gregorianCal.setMonth(gregorianCal.getMonth() - 1);
}
break;
}
} else if (position > CenterPage[0]) {
switch (position % 3) {
case 0:
gregorianCal.set(prevGregorianCal);
if (gregorianCal.getMonth() == 12) {
gregorianCal.setMonth(1);
gregorianCal.setYear(gregorianCal.getYear() + 1);
} else {
gregorianCal.setMonth(gregorianCal.getMonth() + 1);
}
break;
case 1:
nextGregorianCal.set(gregorianCal);
if (nextGregorianCal.getMonth() == 12) {
nextGregorianCal.setMonth(1);
nextGregorianCal.setYear(nextGregorianCal.getYear() + 1);
} else {
nextGregorianCal.setMonth(nextGregorianCal.getMonth() + 1);
}
break;
case 2:
prevGregorianCal.set(nextGregorianCal);
if (prevGregorianCal.getMonth() == 12) {
prevGregorianCal.setMonth(1);
prevGregorianCal.setYear(prevGregorianCal.getYear() + 1);
} else {
prevGregorianCal.setMonth(prevGregorianCal.getMonth() + 1);
}
break;
}
}
CenterPage[0] = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
i hope you can use this code
my site https://mohammadhosseinaref.ir
public static string PersianDayOfWeek(DayOfWeek dayOfWeek)
{
switch (dayOfWeek)
{
case DayOfWeek.Sunday:
return "یکشنبه";
case DayOfWeek.Monday:
return "دوشنبه";
case DayOfWeek.Tuesday:
return "سه شنبه";
case DayOfWeek.Wednesday:
return "چهار شنبه";
case DayOfWeek.Thursday:
return "پنج شنبه";
case DayOfWeek.Friday:
return "جمعه";
case DayOfWeek.Saturday:
return "شنبه";
default:
return null;
}
}
public static Dictionary<int, string> ListOfPersianDayOfMonth(int month, int years)
{
Dictionary<int, string> dicDays = new Dictionary<int, string>();
PersianCalendar p = new PersianCalendar();
var dates = Enumerable.Range(1, p.GetDaysInMonth(years, month))
.Select(day => ParsePersianToGorgian(years + "/" + month + "/" + day))
.ToList();
foreach (var item in dates)
{
var day = GeorgianToPersian(item.Value, ShowMode.OnlyDate);
dicDays.Add(int.Parse(day.Split('/')[2]), DayPersian(item.Value.DayOfWeek) + " " + day);
}
return dicDays;
}
Related
Hi I want to open a activity when a if statement comes true. like "if gameStatus are equal to 12, then open scoreActivity". The Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import java.util.Random;
import android.os.Build;
import android.os.Handler;
public class Game6x4Activity extends AppCompatActivity implements View.OnClickListener {
private int numberOfElements;
private int[] buttonGraphicLocations;
private MemoryButton selectedButton1;
private MemoryButton selectedButton2;
private boolean isBusy = false;
public int gameStatus;
public int gameScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_mode);
gameScore = 0;
gameStatus = 0;
GridLayout gridLayout = (GridLayout)findViewById(R.id.grid_layout_6x4);
int numColumns = gridLayout.getColumnCount();
int numRow = gridLayout.getRowCount();
numberOfElements = numColumns * numRow;
MemoryButton[] buttons = new MemoryButton[numberOfElements];
int[] buttonGraphics = new int[numberOfElements / 2];
buttonGraphics[0] = R.drawable.card1;
buttonGraphics[1] = R.drawable.card2;
buttonGraphics[2] = R.drawable.card3;
buttonGraphics[3] = R.drawable.card4;
buttonGraphics[4] = R.drawable.card5;
buttonGraphics[5] = R.drawable.card6;
buttonGraphics[6] = R.drawable.card7;
buttonGraphics[7] = R.drawable.card8;
buttonGraphics[8] = R.drawable.card9;
buttonGraphics[9] = R.drawable.card10;
buttonGraphics[10] = R.drawable.card11;
buttonGraphics[11] = R.drawable.card12;
buttonGraphicLocations = new int[numberOfElements];
shuffleButtonGraphics();
for(int r=0; r < numRow; r++)
{
for(int c=0; c <numColumns; c++)
{
MemoryButton tempButton = new MemoryButton(this, r, c, buttonGraphics[buttonGraphicLocations[r * numColumns + c]]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tempButton.setId(View.generateViewId());
}
tempButton.setOnClickListener(this);
buttons[r * numColumns + c] = tempButton;
gridLayout.addView(tempButton);
}
}
}
protected void shuffleButtonGraphics(){
Random rand = new Random();
for (int i=0; i < numberOfElements; i++)
{
buttonGraphicLocations[i] = i % (numberOfElements / 2);
}
for (int i=0; i < numberOfElements; i++)
{
int temp = buttonGraphicLocations[i];
int swapIndex = rand.nextInt(16);
buttonGraphicLocations[i] = buttonGraphicLocations[swapIndex];
buttonGraphicLocations[swapIndex] = temp;
}
}
private int buttonGraphicLocations(int i) {
return 0;
}
#Override
public void onClick(View view) {
if(isBusy) {
return;
}
MemoryButton button = (MemoryButton) view;
if(button.isMatched) {
return;
}
if(selectedButton1 == null)
{
selectedButton1 = button;
selectedButton1.flip();
return;
}
if(selectedButton1.getId()== button.getId())
{
return;
}
if (selectedButton1.getFrontDrawableId()== button.getFrontDrawableId())
{
button.flip();
button.setMatched(true);
if (selectedButton1 != null) {
selectedButton1.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
if (selectedButton2 != null) {
selectedButton2.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
gameStatus = gameStatus + 1;
gameScore = gameScore + 10;
if (gameStatus == 12){
Intent it = new Intent(Game6x4Activity.this, ActivityScore.class);
startActivity(it);
}
selectedButton1 = null;
return;
}
else
{
selectedButton2 = button;
selectedButton2.flip();
isBusy = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run(){
selectedButton2.flip();
selectedButton1.flip();
selectedButton1 = null;
selectedButton2 = null;
isBusy = false;
}
},500);
return;
}
}
}
The activity that i want to open will show to the player his score. the activity is equal to all game modes, there will be some test to the app understant what path should go on. test like this one:
"
if (gameStatus == 12) {
gameScore = gameScore*55;
TextView scoreText = (TextView) findViewById(R.id.textView8);
scoreText.setText(gameScore);
}
else if (gameStatus == 15){
"
There are 4 game modes: This is the 6x4 game, where we can find 24 cards (12 images).
else if (gameStatus == 15){
Intent intent = new Intent(Game6x4Activity.this, NextActivity.class);
startActivity(intent);
}
I think, you are asking for this. You can pass value to another activity with
intent.putExtra("key",desired value);
I have an issue.I have custom listView which has many child and also have another custom listview in it.All data which is display in both listView is coming from database.My Problem is that When I scroll My main ListView it stucks for a while and then scroll.I uploaded My all code here.
My Main Activity class:
public class TransactionListMonthWise<DisplayYear> extends TopParentActivity {
ListView statement;
ArrayList<DisplayMonth> status;
ArrayList<DisplayYear> yearstatus;
addBankTransactionList mAdapter;
TextView tvBankName, tvBalance, tvBankAccNoForHistory;
String monthname;
String monthName;
int yearName;
String bankname, amount, accno;
Date theDate;
String currencySymbl, cur_sym;
EPreferences epref;
String TotalBalance, BankBalance, finalTotalIncome;
Toolbar toolbarTransactionListMonthWise;
boolean loadingMore = false;
int itemsPerPage = 2;
DisplayMonth monthNameInAdapter;
int month;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction_monthwise);
bindview();
init();
addListener();
}
private void init() {
epref = EPreferences.getInstance(TransactionListMonthWise.this);
getPrefData();
Intent intent = getIntent();
bankname = intent.getStringExtra("NAME");
tvBankName.setText(bankname);
TotalBalance = String.valueOf(intent.getDoubleExtra("BALANCE", 0.0));
BankBalance = new BigDecimal(TotalBalance).toPlainString();
DecimalFormat decimalFormatIncome = new DecimalFormat("0.#");
finalTotalIncome = decimalFormatIncome.format(Double
.valueOf(TotalBalance));
tvBalance.setText(currencySymbl
+ " "
+ String.format("%,.00f",
(double) Double.parseDouble(finalTotalIncome)));
// tvBalance.setText(amount + " " + currencySymbl);
Log.i("symbol", currencySymbl);
accno = intent.getStringExtra("ACCNO");
status = new ArrayList<DisplayMonth>();
yearstatus = new ArrayList<DisplayYear>();
tvBankAccNoForHistory.setText("xxxxx"
+ intent.getStringExtra("ACC_NUMBER"));
Utils.BANK_ACC_NUM = intent.getStringExtra("ACC_NUMBER");
Utils.BANK_NAME_DISP = bankname;
setSupportActionBar(toolbarTransactionListMonthWise);
this.toolbarTransactionListMonthWise
.setNavigationIcon(R.drawable.ic_arrow_back_white100);
getSupportActionBar().setTitle(bankname + " History");
}
private void bindview() {
toolbarTransactionListMonthWise = (Toolbar) findViewById(R.id.toolbarTransactionListMonthWise);
statement = (ListView) findViewById(R.id.list_transaction_view);
tvBankName = (TextView) findViewById(R.id.tvBankNameForHistory);
tvBalance = (TextView) findViewById(R.id.tvNetBalanceForHistory);
tvBankAccNoForHistory = (TextView) findViewById(R.id.tvBankAccNoForHistory);
}
private void addListener() {
statement.setOnScrollListener(new AbsListView.OnScrollListener() {
int mLastFirstVisibleItem;
boolean mIsScrollingUp;
#Override
public void onScrollStateChanged(AbsListView view, int scrollstate) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount)) {
new MailSender().execute();
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(TransactionListMonthWise.this,
BankList.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private String getMonth(int month1) {
switch (month1) {
case 1:
monthname = "Jan";
break;
case 2:
monthname = "Feb";
break;
case 3:
monthname = "Mar";
break;
case 4:
monthname = "Apr";
break;
case 5:
monthname = "May";
break;
case 6:
monthname = "Jun";
break;
case 7:
monthname = "Jul";
break;
case 8:
monthname = "Aug";
break;
case 9:
monthname = "Sep";
break;
case 10:
monthname = "Oct";
break;
case 11:
monthname = "Nov";
break;
case 12:
monthname = "Dec";
break;
default:
break;
}
return monthname;
}
private int getYear(int years) {
switch (years) {
case 1:
years = 2011;
break;
case 2:
years = 2012;
break;
case 3:
years = 2013;
break;
case 4:
years = 2014;
break;
case 5:
years = 2015;
break;
case 6:
years = 2016;
break;
default:
break;
}
return years;
}
private void getPrefData() {
cur_sym = epref.getPreferencesStr(epref.KEY_CURRENCY, "India");
Log.d("vaaaaa", " == " + cur_sym);
if (cur_sym.equalsIgnoreCase("India")) {
currencySymbl = getResources().getString(R.string.India);
} else if (cur_sym.equalsIgnoreCase("US")) {
currencySymbl = getResources().getString(R.string.United_States);
} else if (cur_sym.equalsIgnoreCase("Japan")) {
currencySymbl = getResources().getString(R.string.Japan);
} else if (cur_sym.equalsIgnoreCase("England")) {
currencySymbl = getResources().getString(R.string.England_pound);
} else if (cur_sym.equalsIgnoreCase("Costa Rica")) {
currencySymbl = getResources().getString(R.string.Costa);
} else if (cur_sym.equalsIgnoreCase("UK")) {
currencySymbl = getResources().getString(R.string.United);
} else if (cur_sym.equalsIgnoreCase("Phillipines")) {
currencySymbl = getResources().getString(R.string.Philippines);
} else if (cur_sym.equalsIgnoreCase("Mangolia")) {
currencySymbl = getResources().getString(R.string.Macedonia);
} else if (cur_sym.equalsIgnoreCase("Australia")) {
currencySymbl = getResources().getString(R.string.Australia);
} else if (cur_sym.equalsIgnoreCase("Europ")) {
currencySymbl = getResources().getString(R.string.Euro);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public class MailSender extends AsyncTask<Void, Integer, Integer> {
Dialog progress;
#SuppressLint("ResourceAsColor")
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new Dialog(TransactionListMonthWise.this,
R.style.AppDialogExit);
progress.requestWindowFeature(Window.FEATURE_NO_TITLE);
progress.show();
progress.setContentView(R.layout.custom_loading_dialog);
TextView tv = (TextView) progress.findViewById(R.id.tv);
tv.setText("Mail is sending...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
}
#Override
protected Integer doInBackground(Void... params) {
final RelativeLayout footerView = (RelativeLayout) findViewById(R.id.loadItemsLayout_recyclerView);
Calendar cal = Calendar.getInstance();
month = cal.get(Calendar.MONTH) + 1;
// int year = cal.get(Calendar.YEAR) - 10;
int currentYear = cal.get(Calendar.YEAR);
Log.d("viewMonths", "month is" + month + " " + currentYear);
for (int j = month; j > 0; j--) {
monthNameInAdapter = new DisplayMonth();
monthName = getMonth(j);
monthNameInAdapter.setMonth(monthName);
status.add(monthNameInAdapter);
}
mAdapter = new addBankTransactionList(getApplicationContext(),
month, status, bankname, accno, currentYear, amount);
return 0;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
// progress.dismiss();
if (progress != null) {
progress.dismiss();
progress = null;
}
try {
statement.setAdapter(mAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Main Xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
android:fitsSystemWindows="true"
android:gravity="center"
android:orientation="vertical" >
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbarTransactionListMonthWise"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="?colorPrimary"
android:minHeight="?actionBarSize"
android:paddingRight="10dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" >
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true" >
<RelativeLayout
android:id="#+id/rlBankNameAndBalance"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#color/green_100"
android:clickable="true"
android:gravity="right"
android:orientation="vertical"
android:paddingLeft="#dimen/main_list_data_disp_padding_left"
android:paddingRight="#dimen/main_list_data_disp_padding_right"
android:paddingTop="#dimen/main_list_data_disp_padding_top" >
<TextView
android:id="#+id/tvBankNameForHistory"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/iconId"
android:text="#string/BankBalance"
android:textColor="#color/gray_900"
android:textSize="#dimen/main_list_data_disp_text_size" />
<TextView
android:id="#+id/tvBankAccNoForHistory"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvBankNameForHistory"
android:text="#string/BankBalance"
android:textColor="#color/gray_500"
android:textSize="14sp" />
<TextView
android:id="#+id/tvNetBalanceForHistory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textColor="#color/gray_900"
android:textSize="#dimen/main_list_data_disp_text_size" />
</RelativeLayout>
</android.support.v7.widget.CardView>
<ListView
android:id="#+id/list_transaction_view"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="2dp"
android:scrollbars="none" />
<include
android:id="#+id/loadItemsLayout_recyclerView"
android:layout_width="fill_parent"
android:layout_height="110dp"
android:layout_alignParentBottom="true"
layout="#layout/progress_layout"
android:visibility="gone" />
Main Adapter Class:
public class addBankTransactionList extends BaseAdapter {
// Activity activityCategory;
static ArrayList<DisplayMonth> monthName;
// ArrayList<DisplayYear> yearName;
ArrayList<Expense> expense;
ArrayList<Income> incomes, Arr;
#SuppressWarnings("rawtypes")
ArrayList<String> arrDateDebit, arrDateCredit;
ArrayList<Double> arrAmountDebit, arrAmountCredit;
Context contextAddBank;
int CurrentMonth;
String bankNameForMatch, months, allyear, SystemMonthInString, amount,
bankAccNoForMatch;
int monthname;
String currencySymbl, cur_sym;
String date = "", thirdYear;
String monthNameInString;
EPreferences epref;
ArrayList<Income> tempIncomeses = new ArrayList<Income>();
String dateIncome, dateExpense;
Double expenseAmount, incomeAmount;
DataBaseAdapter adapter;
// private String ;
int monthNameInStringExpense, monthNameInStringIncome;
int yr, year;
int monthsInIntIncome, dateInIntIncome, yearInIntIncome,
monthsInIntExpense;
String convertDate;
// private ArrayList<Income> tempincomes = new ArrayList<Income>();
List list;
Date date1;
String emptyExpenseAmount, emptyIncomeAmount;
FilterData data;
private String bankname, accno;
public static Boolean isScrolling = true;
public static class ViewHolder {
public TextView tvDate, tvIncomeMoney, tvExpenseMoney,
tvRecordnotFound, tvIncomeSymblIncomeDisp, tvTransactionType,
tvTransactionDate, tvTransactionAmount, tvMoneyCurrencyExpense,
tvMoneyCurrencyIncome;
ListView rvList;
}
public addBankTransactionList(Context mcontext, int month,
ArrayList<DisplayMonth> status, String bankname, String bankAccNo,
int year, String amt) {
super();
this.contextAddBank = mcontext;
monthName = status;
CurrentMonth = month;
bankNameForMatch = bankname;
bankAccNoForMatch = bankAccNo;
yr = year;
amount = amt;
}
public boolean setListViewHeightBasedOnItems(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
int numberOfItems = listAdapter.getCount();
Log.i("TotalRecord", numberOfItems + "");
int totalItemsHeight = 0;
for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
View item = listAdapter.getView(itemPos, null, listView);
item.measure(0, 0);
totalItemsHeight += item.getMeasuredHeight();
}
int totalDividersHeight = listView.getDividerHeight()
* (numberOfItems - 1);
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalItemsHeight + totalDividersHeight;
listView.setLayoutParams(params);
listView.requestLayout();
listView.setClickable(false);
listView.setEnabled(false);
return true;
} else {
return false;
}
}
private void getPrefData() {
cur_sym = epref.getPreferencesStr(epref.KEY_CURRENCY, "India");
Log.d("vaaaaa", " == " + cur_sym);
if (cur_sym.equalsIgnoreCase("India")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.India);
} else if (cur_sym.equalsIgnoreCase("US")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.United_States);
} else if (cur_sym.equalsIgnoreCase("Japan")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Japan);
} else if (cur_sym.equalsIgnoreCase("England")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.England_pound);
} else if (cur_sym.equalsIgnoreCase("Costa Rica")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Costa);
} else if (cur_sym.equalsIgnoreCase("UK")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.United);
} else if (cur_sym.equalsIgnoreCase("Phillipines")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Philippines);
} else if (cur_sym.equalsIgnoreCase("Mangolia")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Macedonia);
} else if (cur_sym.equalsIgnoreCase("Australia")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Australia);
} else if (cur_sym.equalsIgnoreCase("Europ")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Euro);
}
}
private int getMonthName(String month1) {
switch (month1.toLowerCase().toString()) {
case "Jan":
monthname = 1;
break;
case "Feb":
monthname = 2;
break;
case "Mar":
monthname = 3;
break;
case "Apr":
monthname = 4;
break;
case "May":
monthname = 5;
break;
case "Jun":
monthname = 6;
break;
case "Jul":
monthname = 7;
break;
case "Aug":
monthname = 8;
break;
case "Sep":
monthname = 9;
break;
case "Oct":
monthname = 10;
break;
case "Nov":
monthname = 11;
break;
case "Dec":
monthname = 12;
break;
default:
break;
}
return monthname;
}
#Override
public int getCount() {
return monthName.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View conView, ViewGroup parent) {
ViewHolder vh;
if (conView == null) {
conView = LayoutInflater.from(contextAddBank).inflate(
R.layout.transaction_list, null, false);
vh = new ViewHolder();
vh.tvDate = (TextView) conView.findViewById(R.id.tvDate);
vh.rvList = (ListView) conView
.findViewById(R.id.lvDisplayExpenseList);
vh.tvIncomeMoney = (TextView) conView
.findViewById(R.id.tvIncomeMoney);
vh.tvExpenseMoney = (TextView) conView
.findViewById(R.id.tvExpenseMoney);
vh.tvRecordnotFound = (TextView) conView
.findViewById(R.id.tvrecordnotFound);
vh.tvIncomeSymblIncomeDisp = (TextView) conView
.findViewById(R.id.tvIncomeSymblIncomeDisp);
vh.tvMoneyCurrencyExpense = (TextView) conView
.findViewById(R.id.tvMoneyCurrencyExpense);
vh.tvMoneyCurrencyIncome = (TextView) conView
.findViewById(R.id.tvMoneyCurrencyIncome);
adapter = new DataBaseAdapter(contextAddBank);
arrDateDebit = new ArrayList<String>();
arrAmountDebit = new ArrayList<Double>();
arrDateCredit = new ArrayList<String>();
arrAmountCredit = new ArrayList<Double>();
epref = EPreferences.getInstance(contextAddBank);
incomes = new ArrayList<Income>();
expense = new ArrayList<Expense>();
getPrefData();
vh.tvMoneyCurrencyExpense.setText(currencySymbl);
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
adapter.open();
adapter.close();
conView.setTag(vh);
} else {
vh = (ViewHolder) conView.getTag();
}
expense.clear();
incomes.clear();
arrDateCredit.clear();
arrAmountCredit.clear();
arrDateDebit.clear();
arrAmountDebit.clear();
adapter.open();
// viewHolder.rvList.setAdapter(Adapter);
incomes = adapter.read_income();
expense = adapter.read_expense();
double totalExpense = 0.0;
double totalIncome = 0.0;
DisplayMonth month = monthName.get(position);
vh.tvDate.setText(month.getMonth() + " " + yr);
months = month.getMonth();
Log.d("tagNameAdapter",
"name is " + bankNameForMatch + ":::" + month.getMonth());
Log.d("expencesize", "size is " + expense.size());
// expense = adapter.read_expense_with_bankName(bankNameForMatch,
// bankAccNoForMatch);
if (expense.size() > 0) {
for (int l = 0; l < expense.size(); l++) {
Log.d("tagbankfil",
"" + bankNameForMatch + "=="
+ expense.get(l).getBankname() + " AND "
+ expense.get(l).getAccno() + "=="
+ bankAccNoForMatch);
if (bankNameForMatch.equals(expense.get(l).getBankname())
&& bankAccNoForMatch.substring(
bankAccNoForMatch.length() - 3)
.equalsIgnoreCase(
expense.get(l)
.getAccno()
.substring(
expense.get(l)
.getAccno()
.length() - 3))) {
dateExpense = expense.get(l).getDate();
expenseAmount = expense.get(l).getAmount();
Log.i("ExpenseAmount", expenseAmount + ":::::"
+ dateExpense);
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
StringTokenizer tokensIncome = new StringTokenizer(
dateExpense, "-");
String firstDate = tokensIncome.nextToken();
String secondMonth = tokensIncome.nextToken();
thirdYear = tokensIncome.nextToken();
monthsInIntExpense = Integer.parseInt(secondMonth);
int totalYear = Integer.parseInt(thirdYear);
Log.i("MonthNameExpense", totalYear + "");
Log.i("MonthSplitExpense", firstDate + " " + secondMonth
+ " " + thirdYear);
// for (int jmon = 0; jmon < expense.size(); jmon++) {
Log.i("loopTimes", "Check");
SimpleDateFormat sdfSource = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateVal = null;
Log.i("axisbankdateval", dateVal + "");
try {
dateVal = sdfSource.parse(dateExpense);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd-MMM-yyyy");
convertDate = sdfDestination.format(dateVal);
String[] parts = convertDate.split("-");
String transactionMonth = parts[1];
String transactionYear = parts[2];
Log.i("allYear", year + " ");
monthNameInStringExpense = getMonthName(transactionMonth);
Log.i("finddate", convertDate + ":::" + transactionMonth
+ ":::" + monthNameInStringExpense + "::"
+ transactionYear);
Log.d("tagmonth", "" + month.getMonth() + " ::: "
+ transactionMonth + " ---- " + totalYear + "::::"
+ year);
if (month.getMonth().contains(transactionMonth)
&& totalYear == year) {
emptyExpenseAmount = vh.tvExpenseMoney.getText()
.toString();
Log.i("dateAmount", " " + expense.get(l).getAmount()
+ " " + expense.get(l).getDate());
arrDateDebit.add(expense.get(l).getDate());
arrAmountDebit.add(expense.get(l).getAmount());
totalExpense += expense.get(l).getAmount();
DecimalFormat decimalFormatExpense = new DecimalFormat(
"0.#");
String finalTotalExpense = decimalFormatExpense
.format(Double.valueOf(totalExpense));
String valTvExpenseAmt = new BigDecimal(
finalTotalExpense).toPlainString();
vh.tvExpenseMoney.setText(String.format("%,.00f",
(double) Double.parseDouble(valTvExpenseAmt))
+ " " + currencySymbl);
if (totalExpense == 0.0) {
vh.tvExpenseMoney.setText("0.0");
vh.tvMoneyCurrencyExpense.setText(currencySymbl);
} else {
if (vh.tvRecordnotFound.getVisibility() == View.VISIBLE) {
vh.tvRecordnotFound.setVisibility(View.GONE);
vh.tvMoneyCurrencyExpense
.setVisibility(View.INVISIBLE);
vh.tvExpenseMoney.setText(" " + totalExpense
+ " " + currencySymbl);
vh.tvMoneyCurrencyExpense
.setText(currencySymbl);
}
}
}
}
}
}
if (incomes.size() > 0) {
for (int j = 0; j < incomes.size(); j++) {
Log.d("tagbankfil",
"" + bankNameForMatch + "=="
+ incomes.get(j).getIncome_bankname() + " AND "
+ incomes.get(j).getIncome_accno() + "=="
+ bankAccNoForMatch);
if (bankNameForMatch
.equals(incomes.get(j).getIncome_bankname())
&& bankAccNoForMatch
.substring(bankAccNoForMatch.length() - 3)
.equalsIgnoreCase(
incomes.get(j)
.getIncome_accno()
.substring(
incomes.get(j)
.getIncome_accno()
.length() - 3))) {
dateIncome = incomes.get(j).getIncome_date();
incomeAmount = incomes.get(j).getIncome_amount();
Log.i("IncomeAmount", incomeAmount + ":::::" + dateIncome);
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
StringTokenizer tokensIncome = new StringTokenizer(
dateIncome, "-");
String firstDate = tokensIncome.nextToken();
String secondMonth = tokensIncome.nextToken();
thirdYear = tokensIncome.nextToken();
monthsInIntIncome = Integer.parseInt(thirdYear);
int totalYear = Integer.parseInt(thirdYear);
Log.i("MonthNameIncome", monthsInIntIncome + " " + ""
+ monthNameInStringIncome + " " + dateIncome + " "
+ incomes.size() + "" + totalYear);
Log.i("MonthSplitIncome", firstDate + " " + secondMonth
+ " " + thirdYear);
Log.i("loopTimes", "Check");
SimpleDateFormat sdfSource = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateVal = null;
Log.i("axisbankdateval", dateVal + "");
try {
dateVal = sdfSource.parse(dateIncome);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd-MMM-yyyy");
convertDate = sdfDestination.format(dateVal);
String[] parts = convertDate.split("-");
String transactionMonth = parts[1];
String transactionYear = parts[2];
monthNameInStringIncome = getMonthName(transactionMonth);
Log.i("finddate", convertDate + "::" + monthname + "::"
+ monthNameInStringIncome);
if (month.getMonth().contains(transactionMonth)
&& totalYear == year) {
emptyIncomeAmount = vh.tvIncomeMoney.getText()
.toString();
arrDateCredit.add(incomes.get(j).getIncome_date());
arrAmountCredit.add(incomes.get(j).getIncome_amount());
totalIncome += incomes.get(j).getIncome_amount();
DecimalFormat decimalFormatIncome = new DecimalFormat(
"0.#");
String finalTotalIncome = decimalFormatIncome
.format(Double.valueOf(totalIncome));
String valTvIncomeAmt = new BigDecimal(finalTotalIncome)
.toPlainString();
vh.tvIncomeMoney.setText(String.format("%,.00f",
(double) Double.parseDouble(valTvIncomeAmt))
+ " ");
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
if (totalIncome == 0.0) {
vh.tvIncomeMoney.setText("0.0");
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
} else {
if (vh.tvRecordnotFound.getVisibility() == View.VISIBLE) {
vh.tvRecordnotFound.setVisibility(View.GONE);
vh.tvIncomeMoney.setText(" " + totalIncome
+ " " + currencySymbl);
}
}
}
}
}
Log.i("currentYear", year + "" + thirdYear);
}
CategoryList categoryListAdapter = new CategoryList(contextAddBank,
arrDateDebit, arrAmountDebit, arrDateCredit, arrAmountCredit);
vh.rvList.setAdapter(categoryListAdapter);
setListViewHeightBasedOnItems(vh.rvList);
vh.rvList.setScrollContainer(true);
categoryListAdapter.notifyDataSetChanged();
return conView;
}
}
Your application is sticking when you're scrolling down because you're doing all of that processing upon every move when you scroll. Every row is running through the statements of your getView method every single time it's brought back to the screen, phones don't have enough processing power for all of that. You need to separate all of that into a different class, and then load it into the adapter in a smaller data set so that all it has to do is display it. Basically, you're doing processing in the UI(Main) thread, which is bad.
Given how you also have nested listViews, changing to an expandedListView would also be a lot easier for you in the grand scheme of things, may do the job better. Here's a tutorial for it: https://www.youtube.com/watch?v=BkazaAeeW1Q
I am creating calendar which contains events and I want to show total no of events on particular date. I am using
CalendarAdapter.java class. For showing total no. of events count (like notification bubble) on date I am using
Badge.java class. Now problem is that badge is apply on Calendars dates which current month is showing first,
after changing month then that badge is not remove from next month calendar.
Calendar Adapter:
package vyClean.wemecalendar.adapters;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import vyClean.wemecalendar.activity.Event1;
import vyClean.wemecalendar.util.BadgeView;
import vyClean.wemecalendar.util.BadgeView1;
import vyClean.wemecalendar.util.CalendarEvent;
import vyClean.wemecalendar.R;
import vyClean.wemecalendar.util.ToastMessage;
public class CalendarAdapter extends BaseAdapter {
private Context context;
private java.util.Calendar month;
public GregorianCalendar pmonth;
/*-----------calendar instance for previous month for getting complete view-------------------*/
public GregorianCalendar pmonthmaxset;
private GregorianCalendar selectedDate;
int firstDay;
int maxWeeknumber;
int maxP;
int calMaxP;
int mnthlength;
String itemvalue, curentDateString;
DateFormat df;
public static TextView textno;
RelativeLayout cal_item_ll;
private ArrayList<String> items;
public static List<String> day_string;
private View previousView;
private View getView;
public ArrayList<CalendarEvent> event_calendar_arr;
public CalendarAdapter(Context context, GregorianCalendar monthCalendar, ArrayList<CalendarEvent> event_calendar_arr) {
this.event_calendar_arr = event_calendar_arr;
CalendarAdapter.day_string = new ArrayList<>();
Locale.setDefault(Locale.getDefault());
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
this.context = context;
month.set(GregorianCalendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<>();
df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
curentDateString = df.format(selectedDate.getTime());
refreshDays();
}
public int getCount() {
return day_string.size();
}
public Object getItem(int position) {
return day_string.get(position);
}
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
getView = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getView = vi.inflate(R.layout.cal_item, parent, false);
cal_item_ll = (RelativeLayout) getView.findViewById(R.id.cal_item_ll);
//textno = (TextView) getView.findViewById(R.id.textno);
}
dayView = (TextView) getView.findViewById(R.id.date);
String[] separatedTime = day_string.get(position).split("-");
String gridvalue = separatedTime[2].replaceFirst("^0*", "");
if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
dayView.setTextColor(Color.GRAY);
dayView.setClickable(false);
dayView.setFocusable(false);
} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
dayView.setTextColor(Color.GRAY);
dayView.setClickable(false);
dayView.setFocusable(false);
} else {
// setting curent month's days in blue color.
dayView.setTextColor(Color.parseColor("#ff69b4"));
}
if (day_string.get(position).equals(curentDateString)) {
getView.setBackgroundColor(Color.CYAN);
} else {
getView.setBackgroundColor(Color.WHITE);
}
dayView.setText(gridvalue);
// create date string for comparison
String date = day_string.get(position);
if (date.length() == 1) {
date = "0" + date;
}
String monthStr = "" + (month.get(GregorianCalendar.MONTH) + 1);
if (monthStr.length() == 1) {
monthStr = "0" + monthStr;
}
int len = CalendarEvent.event_calendar_arr.size();
HashSet<String> eventListSet1 = new HashSet<>();
int flag = 0;
for (int j = 0; j < len; j++) {
//textno.setTextColor(Color.WHITE);
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(j);
if (day_string.get(position).equals(cal_event.getEventFromDate())) {
eventListSet1.add(cal_event.getEventCateId());
flag = 1;
}
}
if (flag == 1) {
setEventView(getView, position, dayView, eventListSet1);
/*----------call badgeview here--------*/
/*----------call badgeview on linear layout (cal_item_ll) which is inside getview--------*/
BadgeView badge = new BadgeView(context, cal_item_ll);
badge.setText("1");
badge.show();
}
System.out.println("eventListSet1:" + eventListSet1);
return getView;
}
public View setSelected(View view, int pos) {
if (previousView != null) {
// previousView.setBackgroundColor(Color.CYAN);
previousView.setBackgroundColor(Color.WHITE);
}
view = previousView;
// view.setBackgroundColor(Color.CYAN);
int len = day_string.size();
if (len > pos) {
if (day_string.get(pos).equals(curentDateString)) {
} else {
previousView = view;
}
}
return view;
}
public void refreshDays() {
// clear items
items.clear();
day_string.clear();
Locale.setDefault(Locale.getDefault());
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
// allocating maximum row number for the gridview.
mnthlength = maxWeeknumber * 7;
maxP = getMaxP(); // previous month maximum day 31,30....
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
//Calendar instance for getting a complete gridview including the three month's (previous,current,next) dates.
pmonthmaxset = (GregorianCalendar) pmonth.clone();
//setting the start date as previous month's required date.
pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);
// filling calendar gridview.
for (int n = 0; n < mnthlength; n++) {
itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(GregorianCalendar.DATE, 1);
System.out.println(" 214 itemvale :" + itemvalue);
day_string.add(itemvalue);
}
}
private int getMaxP() {
int maxP;
if (month.get(GregorianCalendar.MONTH) == month
.getActualMinimum(GregorianCalendar.MONTH)) {
pmonth.set((month.get(GregorianCalendar.YEAR) - 1),
month.getActualMaximum(GregorianCalendar.MONTH), 1);
} else {
pmonth.set(GregorianCalendar.MONTH,
month.get(GregorianCalendar.MONTH) - 1);
}
maxP = pmonth.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
return maxP;
}
public void setEventView(View v, int pos, TextView txt, HashSet<String> eventListSet1) {
ArrayList<String> eventList = new ArrayList<>();
int len = CalendarEvent.event_calendar_arr.size();
for (int i = 0; i < len; i++) {
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(i);
int len1 = day_string.size();
if (len1 > pos) {
String category = cal_event.getEventCateId();
HashSet<String> eventListSet = new HashSet<String>();
StringTokenizer stR = new StringTokenizer(category, ",");
while (stR.hasMoreTokens()) {
eventListSet.add(stR.nextToken());
}
ArrayList<String> sortedList = new ArrayList(eventListSet1);
Collections.sort(sortedList);
//System.out.println("sortedList:" + sortedList);
StringBuffer CategoryNew = new StringBuffer();
Iterator<String> itr = sortedList.iterator();
while (itr.hasNext()) {
CategoryNew.append(itr.next() + ",");
}
eventList.add(category);
switch (CategoryNew.toString()) {
/* ----------only one category ----------*/
case "1,":
v.setBackgroundResource(R.drawable.gs);
break;
case "2,":
v.setBackgroundResource(R.drawable.se);
break;
case "3,":
v.setBackgroundResource(R.drawable.ge);
break;
case "4,":
v.setBackgroundResource(R.drawable.tuce);
break;
/*----------two category----------*/
case "1,2,":
v.setBackgroundResource(R.drawable.gsse);
break;
case "1,3,":
v.setBackgroundResource(R.drawable.gsge);
break;
case "1,4,":
v.setBackgroundResource(R.drawable.gstuce);
break;
case "2,3,":
v.setBackgroundResource(R.drawable.sege);
break;
case "2,4,":
v.setBackgroundResource(R.drawable.setuce);
break;
case "3,4,":
v.setBackgroundResource(R.drawable.getuce);
break;
/*----------three category----------*/
case "1,2,3,":
v.setBackgroundResource(R.drawable.gssege);
break;
case "1,3,4,":
v.setBackgroundResource(R.drawable.gsgetuce);
break;
case "1,2,4,":
v.setBackgroundResource(R.drawable.gssetuce);
break;
case "2,3,4,":
v.setBackgroundResource(R.drawable.gesetuce);
break;
/*----------four category----------*/
case "1,2,3,4,":
v.setBackgroundResource(R.drawable.gssegetuce);
default:
System.out.println("Invalid event");
break;
}
/*BadgeView1 badge = new BadgeView1(context, cal_item_ll);
badge.setText("1");
badge.show();*/
txt.setTextColor(Color.BLUE);
}
}
}
public void getPositionList(String date, final Activity act) {
final String TAG_EVENT_NAME = "event_name";
final String TAG_EVENT_DESC = "event_desc";
final String TAG_EVENT_FROM_DATE = "event_from_date";
final String TAG_EVENT_TO_DATE = "event_to_date";
final String TAG_EVENT_TIMING = "event_timing";
final String TAG_EVENT_PLACE = "event_place";
final String TAG_EVENT_CATE_ID = "event_cate_id";
String event_name, event_desc, event_from_date;
String event_to_date, event_timing, event_place, event_cate_id;
ArrayList<HashMap<String, String>> event = new ArrayList<>();
int len = CalendarEvent.event_calendar_arr.size();
for (int i = 0; i < len; i++) {
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(i);
event_name = cal_event.getEventName();
event_desc = cal_event.getEventDesc();
event_from_date = cal_event.getEventFromDate();
event_to_date = cal_event.getEventToDate();
event_timing = cal_event.getEventTiming();
event_place = cal_event.getEventPlace();
event_cate_id = cal_event.getEventCateId();
if (date.equals(event_from_date)) {
HashMap<String, String> map = new HashMap<>();
map.put(TAG_EVENT_NAME, event_name);
map.put(TAG_EVENT_DESC, event_desc);
map.put(TAG_EVENT_FROM_DATE, event_from_date);
map.put(TAG_EVENT_TO_DATE, event_to_date);
map.put(TAG_EVENT_TIMING, event_timing);
map.put(TAG_EVENT_PLACE, event_place);
if (event_cate_id.equals(1)) {
map.put(TAG_EVENT_CATE_ID, "General Science");
}
if (event_cate_id.equals(2)) {
map.put(TAG_EVENT_CATE_ID, "Scientific Exhibition");
}
if (event_cate_id.equals(3)) {
map.put(TAG_EVENT_CATE_ID, "General Events");
}
if (event_cate_id.equals(4)) {
map.put(TAG_EVENT_CATE_ID, "Tuce Clubs");
}
if (event_cate_id.equals("")) {
map.put(TAG_EVENT_CATE_ID, "");
}
event.add(map);
}
}
if (event.size() > 0) {
Bundle b = new Bundle();
b.putSerializable("EVENT_LIST", event);
Intent in = new Intent(context, Event1.class);
in.putExtras(b);
context.startActivity(in);
} else {
ToastMessage.toastMessage(context, "On this date there is no event");
}
}
BadgeView.class -
package vyClean.wemecalendar.util;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
public class BadgeView extends TextView {
private Context context;
protected View target;
private ShapeDrawable badgeBg;
public BadgeView(Context context, View target) {
this(context, null, android.R.attr.textViewStyle, target);
}
public BadgeView(Context context, AttributeSet attrs, int defStyle, View target) {
super(context, attrs, defStyle);
init(context, target);
}
private void init(Context context, View target) {
try {
this.context = context;
this.target = target;
//apply defaults
setTypeface(Typeface.DEFAULT_BOLD);
setPadding(7, 0, 7, 0);
setTextColor(Color.WHITE);
if (this.target != null) {
applyTo(this.target);
} else {
show();
}
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
private void applyTo(View target) {
try {
ViewGroup.LayoutParams lp = target.getLayoutParams();
//ViewParent parent = target.getParent();
FrameLayout container = new FrameLayout(context);
// TODO verify that parent is indeed a ViewGroup
ViewGroup group = (ViewGroup) target;
int index = group.indexOfChild(target);
group.removeView(target);
group.addView(container, index,lp);
container.addView(target);
container.addView(this);
group.invalidate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void show() {
try {
if (getBackground() == null) {
if (badgeBg == null) {
badgeBg = getDefaultBackground();
}
setBackgroundDrawable(badgeBg);
}
applyLayoutParams();
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
private ShapeDrawable getDefaultBackground() {
ShapeDrawable drawable = null;
try {
float[] outerR = new float[]{20, 20, 20, 20, 20, 20, 20, 20};
RoundRectShape rr = new RoundRectShape(outerR, null, null);
drawable = new ShapeDrawable(rr);
drawable.getPaint().setColor(Color.BLACK);
} catch (StackOverflowError e) {
e.printStackTrace();
}
return drawable;
}
private void applyLayoutParams() {
try {
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.RIGHT | Gravity.TOP;
setLayoutParams(lp);
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
}
Hello i try to use my own adapter on Gridview.
My problem is that the position in getView is not increasing.
This is my code:
public class WorkourLogBuilder {
String[] values = new String[11];
Context mContext;
Map<Integer, String[]> valuesArray;
int rowsCount = 0;
int mode;
int adappterRowsCount = 0;
static final int AEROBIC = 1;
static final int ANAEROBIC = 0;
public WorkourLogBuilder(Context context, int modeChoosed)
{
mContext = context;
mode = modeChoosed;
valuesArray = new HashMap<Integer, String[]>();
}
public void commintRow()
{
valuesArray.put(rowsCount, values);
rowsCount++;
Log.i("rowsCount", rowsCount+"");
values = new String[11];
}
public void setWorkoutWeight(String value)
{
values[0] = value;
}
public void setSets(String value)
{
values[1] = value;
}
public void setReps(String value)
{
values[2] = value;
}
public void setWorkTime(String value)
{
values[3] = value;
}
public void setWDayTime(String value)
{
values[4] = value;
}
public void setDistance(String value)
{
values[5] = value;
}
public void setSpeed(String value)
{
values[6] = value;
}
public void setRestTime(String value)
{
values[7] = value;
}
public void setCaloires(String value)
{
values[8] = value;
}
public void setHeartBeat(String value)
{
values[9] = value;
}
public void setComment(String value)
{
values[10] = value;
}
public View build()
{
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
View v = inflater.inflate(R.layout.workout_log_row, null, false);
GridView grid = (GridView) v.findViewById(R.id.table);
Log.i("count", valuesArray.size()+"");
grid.setAdapter(new ImageAdapter());
return v;
}
public class ImageAdapter extends BaseAdapter {
public int getCount() {
return (valuesArray.size()+6);
}
public Object getItem(int position) {
return valuesArray.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.i("position", position+"");
if(position < 6)
{
ImageView image = new ImageView(mContext);
if(position < 3)
image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.small_green_apple));
else
image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.anonymous));
image.setScaleType(ImageView.ScaleType.FIT_XY);
return image;
}
TextView textValue = new TextView(mContext);
textValue.setTextColor(Color.BLACK);
GridView.LayoutParams lp = new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT, GridView.LayoutParams.MATCH_PARENT);
textValue.setLayoutParams(lp);
String[] currecntRow = valuesArray.get(adappterRowsCount);
switch(position % 6)
{
case 0:
{
if(adappterRowsCount != 6)
adappterRowsCount++;
if(mode == AEROBIC)
textValue.setText(currecntRow[5]);
else
textValue.setText(currecntRow[0]);
break;
}
case 1:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[3]);
else
textValue.setText(currecntRow[2]);
break;
}
case 2:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[6]);
else
textValue.setText(currecntRow[1]);
break;
}
case 3:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[1]);
else
textValue.setText(currecntRow[7]);
break;
}
case 4:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[7]);
else
textValue.setText(currecntRow[3]);
break;
}
case 5:
{
if(mode == AEROBIC)
textValue.setText(currecntRow[10]);
else
textValue.setText(currecntRow[10]);
break;
}
}
return textValue;
}
}`enter code h
The XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<GridView
android:id="#+id/table"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:numColumns="6" >
</GridView>
</RelativeLayout>
This is where i use WorkourLogBuilder class
public void setTheLogViewTest(String date)
{
String[][] values = data.dayLog(date);
ArrayList<ExpandListGroup> listAll = new ArrayList<ExpandListGroup>();
ArrayList<ExpandListChild> listChilds = new ArrayList<ExpandListChild>();
ExpandListGroup group = new ExpandListGroup();
ExpandListChild child = new ExpandListChild();
int length = values[0].length;
WorkourLogBuilder builder = null;
for(int i = 0; i < length; i++)
{
String exrcise = values[3][i];
String restTime;
String setTime;
String weight;
String reps;
String comment;
String sets;
String speed;
String distance;
if (values[9][i] == null || values[9][i].equals(""))
speed = mResources.getString(R.string.Undefined);
else {
if (data.getUnits().equals("metric"))
speed = values[9][i] + " " + mResources.getString(R.string.km_hour);
else
speed = values[9][i] + " " + mResources.getString(R.string.miles_hour);
}
if (values[10][i] == null || values[10][i].equals(""))
restTime = mResources.getString(R.string.Undefined);
else
restTime = getTimesPharsed(values[10][i]);
if (values[6][i] == null || values[6][i].equals(""))
setTime = mResources.getString(R.string.Undefined);
else
setTime = getTimesPharsed(values[6][i]);
if (values[4][i] == null || values[4][i].equals(""))
weight = mResources.getString(R.string.Undefined);
else {
if (data.getUnits().equals("metric"))
weight = values[4][i] + " " + mResources.getString(R.string.kg);
else
weight = values[4][i] + " " + mResources.getString(R.string.lbs);
}
if (values[5][i] == null || values[5][i].equals(""))
reps = mResources.getString(R.string.Undefined);
else
reps = values[5][i];
if (values[11][i] == null || values[11][i].equals(""))
comment = mResources.getString(R.string.Undefined);
else
comment = values[11][i];
if (values[12][i] == null || values[12][i].equals(""))
sets = mResources.getString(R.string.Undefined);
else
sets = values[12][i] + checkForFailedSets(values[1][i]);
if (values[8][i] == null || values[8][i].equals(""))
distance = mResources.getString(R.string.Undefined);
else {
if (data.getUnits().equals("metric"))
distance = values[8][i] + " " + mResources.getString(R.string.km);
else
distance = values[8][i] + " " + mResources.getString(R.string.miles);
}
if(i == 0)
{
group = new ExpandListGroup();
group.setName(exrcise, this);
Log.i("test", "1");
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
}
else if (i > 0 && exrcise.equals(values[3][i - 1]) == false && i == length - 1 == false)
{
Log.i("test", "2");
View v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
group = new ExpandListGroup();
group.setName(exrcise, this);
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
}
else if (i == length - 1 && exrcise.equals(values[3][i - 1]) == false)
{
Log.i("test", "3");
View v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
group = new ExpandListGroup();
group.setName(exrcise, this);
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
}
else if (i == length - 1 && exrcise.equals(values[3][i - 1]) == true)
{
Log.i("test", "4");
if(data.getAerobic(exrcise))
builder = new WorkourLogBuilder(this, ANAEROBIC);
else
builder = new WorkourLogBuilder(this, AEROBIC);
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
View v = builder.build();
child = new ExpandListChild();
child.setLayouts((RelativeLayout) v);
listChilds.add(child);
group.setItems(listChilds);
listAll.add(group);
}
else
{
Log.i("test", "5");
builder.setWorkoutWeight(weight);
builder.setReps(reps);
builder.setSets(sets);
builder.setWorkTime(setTime);
builder.setRestTime(restTime);
builder.setComment(comment);
builder.setDistance(distance);
builder.setSpeed(speed);
builder.commintRow();
}
}
ExpAdapter = new ExpandListAdapter(DatePage.this, listAll);
ExpandList.setAdapter(ExpAdapter);
}
When i look at the logcat i that the position log is always 0.
Why position is not increasing?
You are not returning from getItem() correctly:
public Object getItem(int position) {
return position;
}
It should be:
public Object getItem(int position) {
return valuesArray.get(position);
}
you have wrong in getItem()
public Object getItem(int position) {
return valuesArray.get(position);
}
it should return an Object not an the position, so basically it is always returning 0
I need help on how to go about and make prev month's days visible (grayed out) on this calendar.
I am getting a present months view here.. but as you can see the previous months days are not visible.I know why.. but how to go about it? also few bugs are there in this present one as well.please help.Posting the code for the custom adapter class:
CalendarAdapter.java
import java.util.ArrayList;
import java.util.Calendar;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CalendarAdapter extends BaseAdapter {
static final int FIRST_DAY_OF_WEEK =0; // Sunday = 0, Monday = 1
private Context mContext;
private java.util.Calendar month;
private Calendar selectedDate;
private ArrayList<String> items;
public CalendarAdapter(Context c, Calendar monthCalendar) {
month = monthCalendar;
selectedDate = (Calendar)monthCalendar.clone();
mContext = c;
month.set(Calendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
refreshDays();
}
public void setItems(ArrayList<String> items) {
for(int i = 0;i != items.size();i++){
if(items.get(i).length()==1) {
items.set(i, "0" + items.get(i));
}
}
this.items = items;
}
public int getCount() {
return days.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_item, null);
}
dayView = (TextView)v.findViewById(R.id.date);
// disable empty days from the beginning
if(days[position].equals("")) {
dayView.setClickable(false);
dayView.setFocusable(false);
//need to show previous months date
}
else {
// mark current day as focused
if(month.get(Calendar.YEAR)== selectedDate.get(Calendar.YEAR) && month.get(Calendar.MONTH)== selectedDate.get(Calendar.MONTH) && days[position].equals(""+selectedDate.get(Calendar.DAY_OF_MONTH))) {
v.setBackgroundResource(R.drawable.date_area);
dayView.setTextColor(Color.parseColor("#FFFFFF"));
}
else {
v.setBackgroundResource(R.drawable.current_date_area);
}
}
dayView.setText(days[position]);
// create date string for comparison
String date = days[position];
if(date.length()==1) {
date = "0"+date;
}
String monthStr = ""+(month.get(Calendar.MONTH)+1);
if(monthStr.length()==1) {
monthStr = "0"+monthStr;
}
// show icon if date is not empty and it exists in the items array
/* ImageView iw = (ImageView)v.findViewById(R.id.date_icon);
if(date.length()>0 && items!=null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
}
else {
iw.setVisibility(View.INVISIBLE);
}*/
return v;
}
public void refreshDays()
{
// clear items
items.clear();
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int)month.get(Calendar.DAY_OF_WEEK);
// figure size of the array
if(firstDay==1){
days = new String[lastDay+(FIRST_DAY_OF_WEEK*6)];
}
else {
days = new String[lastDay+firstDay-(FIRST_DAY_OF_WEEK+1)];
}
int j=FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if(firstDay>1) {
for(j=0;j<firstDay-FIRST_DAY_OF_WEEK;j++) {
days[j] = "";
}
}
else {
for(j=0;j<FIRST_DAY_OF_WEEK*6;j++) {
days[j] = "";
}
j=FIRST_DAY_OF_WEEK*6+1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
for(int i=j-1;i<days.length;i++) {
days[i] = ""+dayNumber;
dayNumber++;
}
}
// references to our items
public String[] days;}
and this is the Activity code on how i am using this adapter:
CalendarView.java
/*some code above*/
/*this is in the OnCreate block*/
adapter = new CalendarAdapter(this, month);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(adapter);
/*some code below*/
and heres my calendar view screen (grid):
CalendarView Screenshot:
To be straight and to the point,All i want is that blank boxes before 1st of the month be filled in with the previous month's last week's days
Declare another calendar
private java.util.Calendar month, prevMonth;
Add a clone to calendar in the constructor
prevMonth = (Calendar) month.clone();
prevMonth.roll(Calendar.MONTH, false);
Then replace the refreshDays with this one.This fills up the blank spaces with the days from the last month and the next month for the first and last week of the current month respectively.
public void refreshDays() {
// clear items
items.clear();
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int) month.get(Calendar.DAY_OF_WEEK);
int maxweek = month.getActualMaximum(Calendar.WEEK_OF_MONTH);
Log.d("CalendarAdapter", String.valueOf(maxweek));
// figure size of the array
/*
* if (firstDay == 1) { days = new String[lastDay + (FIRST_DAY_OF_WEEK *
* 6)]; }
*
* else { days = new String[lastDay + firstDay - (FIRST_DAY_OF_WEEK +
* 1)]; }
*/
days = new String[maxweek * 7];
int j = FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if (firstDay > 1) {
// can be made a bit faster if implemented without this following
// for loop for roll
for (j = 0; j < firstDay - FIRST_DAY_OF_WEEK; j++) {
prevMonth.roll(Calendar.DAY_OF_MONTH, false);
Log.d("CalendarAdapter",
"roll block: " + prevMonth.get(Calendar.DAY_OF_MONTH));
}
for (j = 0; j < firstDay - FIRST_DAY_OF_WEEK; j++) {
// days[j] = "";
prevMonth.roll(Calendar.DAY_OF_MONTH, true);
int dayPrev = prevMonth.get(Calendar.DAY_OF_MONTH);
days[j] = " " + String.valueOf(dayPrev) + " ";
Log.d("CalendarAdapter", "calculation:J if firstDay>1 -- " + j
+ " roll gives:" + dayPrev);
}
} else {
for (j = 0; j < FIRST_DAY_OF_WEEK * 6; j++) {
days[j] = "";
Log.d("CalendarAdapter", "calculation:J if firstDay<1 -- " + j);
}
j = FIRST_DAY_OF_WEEK * 6 + 1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
boolean flag = false;
for (int i = j - 1; i < days.length; i++) {
days[i] = String.valueOf(dayNumber).trim() + ".";
if (flag)
days[i] = String.valueOf(dayNumber).trim();
if (dayNumber == lastDay) {
dayNumber = 0;
flag=true;
}
dayNumber++;
}
}
// references to our items
public String[] days;
}