Я в настоящее время новичок в android разработке, и я нахожусь в процессе создания моего первого приложения. Я застрял на одном хитром кусочке, в котором я пытаюсь реализовать Endless Recycler View.
Я использую представление рециркулятора (в настоящее время) просто для получения текущих дат и отображения их в выводе календаря. Есть две вещи, которые действительно держат меня. Во-первых, не так много документации по использованию представления бесконечного переработчика без базы данных (я планирую, но опять же не прямо сейчас), и не зная, где и как сделать его бесконечным. Реализованный мной просмотрщик recyclerView уже работает, мне просто нужно его бесконечно загружать. Единственные примеры, которые я мог найти, требовали от меня использования базы данных или создания одного гигантского c метода в методе onCreate. Я также попытался реализовать свой собственный setOnScrollListener внутри домашнего класса, но, увы, я не смог заставить его работать.
Ниже приведены желаемые результаты, которые я изобразил в своей голове. Ссылка на картинку интерфейса пользователя
Вот мой код. В идеале я хотел бы сохранить прослушиватель на прокрутке в RecyclerAdapter, так как я, вероятно, буду использовать его позже в других аспектах приложения. Заранее благодарим.
ДОМАШНИЙ КЛАСС
public class Home extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private static final String TAG = "Home Class" ;
//Recycler View Variables and myCalendarClass Variables
private myCalendarClass myCalendarObj;
private int weeksInView = 1; //will need to make this update dynamicallly based on when a user toggles the view
private ArrayList<Calendar> calendarArrayList = new ArrayList<>();
private ArrayList<Integer> iconList = new ArrayList<>();
private ArrayList<Integer> eventCounterList = new ArrayList<>();
//recycler view dynamic loading variables
private RecyclerView calendarRecyclerView;
private boolean isLoading = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
initializeNavMenuButtons();
setViewSpinner();
this.myCalendarObj = new myCalendarClass();
setAllCalendarFields(this.myCalendarObj);
getImagesAndEventCounters();
//Example of the order to call the methods when a user switches the view
//setCalendarItrToCurrentSunday();
//setCalendarArrayList();
//getImagesAndEventCounters();
}
//Recycler view code
//gets images and events to feed into the recycler view
private void getImagesAndEventCounters() {
Log.d(TAG, "initImageBitMaps: called");
ArrayList<Calendar> weekView = getCalendarArrayList();
int daysInView = this.weeksInView * 7;
System.out.println("Days in view " + daysInView + " Weeks In View " + this.weeksInView);
for (int i = 0; i < daysInView; i++) {
calendarArrayList.add(weekView.get(i));
iconList.add(R.id.fitnessIcon);
eventCounterList.add(R.string.XEventsDefault);
iconList.add(R.id.educationIcon);
eventCounterList.add(R.string.XEventsDefault);
iconList.add(R.id.workIcon);
eventCounterList.add(R.string.XEventsDefault);
iconList.add(R.id.personalIcon);
eventCounterList.add(R.string.XEventsDefault);
initRecyclerView();
}
}
//passes data to the parent recycler view and sets the view
private void initRecyclerView() {
//For one recyclerView
this.parentLayoutManager = new GridLayoutManager(this, 7);
//GridLayoutManager layoutManager = parentLayoutManager;
RecyclerView recyclerView = findViewById(R.id.calendarRecyclerView);
recyclerView.setLayoutManager(parentLayoutManager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this,iconList,eventCounterList,weeksInView,calendarArrayList);
recyclerView.setAdapter(adapter);
//ViewSpinner(Drop Down Menu)
private void setViewSpinner(){
Spinner viewSpinner = findViewById(R.id.ViewDropDownButton);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.Calendar_View_List, android.R.layout.simple_spinner_item);
viewSpinner.setAdapter(adapter);
viewSpinner.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
myCalendarClass myCalendarObj;
if(text.equals("Week View")){
myCalendarObj = new myCalendarClass("Week View");
setAllCalendarFields(myCalendarObj);
getImagesAndEventCounters();
this.myCalendarObj = myCalendarObj;
}
else if (text.equals("Biweekly View")){
myCalendarObj = new myCalendarClass("Biweekly View");
setAllCalendarFields(myCalendarObj);
getImagesAndEventCounters();
this.myCalendarObj = myCalendarObj;
}
else if (text.equals("Month View")){
myCalendarObj = new myCalendarClass("Month View");
setAllCalendarFields(myCalendarObj);
getImagesAndEventCounters();
this.myCalendarObj = myCalendarObj;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
//setters
//sets all the local variables needed from myCalendarClass
private void setAllCalendarFields(myCalendarClass c){
this.myCalendarObj = c;
this.calendarArrayList = c.getCalendarArrayList();
this.weeksInView = c.getWeeksInView();
}
//getters
//returns the calendar arraylist
private ArrayList<Calendar> getCalendarArrayList(){
return this.calendarArrayList;
}
РЕАКТОРНЫЙ АДАПТЕР
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private static final String TAG = "RecyclerViewAdapter";
//variables for creating the recyclerView cards
private ArrayList<Integer> iconList;
private ArrayList<Integer> eventCounterList;
private Context mContext;
private int itemCount;
private ArrayList<Calendar> calendarArrayList;
private ArrayList<String> dayStr;
private ArrayList<String> dayNum;
public RecyclerViewAdapter(Context context, ArrayList<Integer> imageList, ArrayList<Integer> eventArray, int weeksInView,ArrayList<Calendar> calendarArrayList){
this.iconList = imageList;
this.eventCounterList = eventArray;
this.mContext = context;
this.itemCount = weeksInView*7;
this.calendarArrayList = calendarArrayList;
setDayStrNDayNum();
}
@NonNull
@Override
//this is the method that actually inflates each individual layout
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateViewHolder: called.");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem,parent,false);
return new ViewHolder(view);
}
@Override
//this is where we bind the data to each individual list items
//essentially all the data and stuff is actually attached in this method to each indiviual list item
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: called");
holder.fitnessIcon.getDrawable();
holder.educationIcon.getDrawable();
holder.personalIcon.getDrawable();
holder.workIcon.getDrawable();
holder.fitnessEventCounter.setText(eventCounterList.get(position));
holder.educationEventCounter.setText(eventCounterList.get(position));
holder.workEventCounter.setText(eventCounterList.get(position));
holder.personalEventCounter.setText(eventCounterList.get(position));
holder.dayString.setText(dayStr.get(position));
holder.dayNum.setText(dayNum.get(position));
}
//returns the amount of items we wish to include in the recycler view (not the individual items within a card layout
// but instead how many cards we wish to include...probably
@Override
public int getItemCount() {
return itemCount;
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView fitnessIcon;
ImageView educationIcon;
ImageView workIcon;
ImageView personalIcon;
TextView dayString;
TextView dayNum;
TextView fitnessEventCounter;
TextView educationEventCounter;
TextView workEventCounter;
TextView personalEventCounter;
public ViewHolder(View itemView){
super(itemView);
//icons within the layout_listitem
fitnessIcon = itemView.findViewById(R.id.fitnessIcon);
educationIcon = itemView.findViewById(R.id.educationIcon);
workIcon = itemView.findViewById(R.id.workIcon);
personalIcon = itemView.findViewById(R.id.personalIcon);
//text fields within the layout_listitem
dayNum = itemView.findViewById(R.id.dayNum);
dayString = itemView.findViewById(R.id.dayStr);
fitnessEventCounter = itemView.findViewById(R.id.fitnessEventCounter);
educationEventCounter = itemView.findViewById(R.id.educationEventCounter);
workEventCounter = itemView.findViewById(R.id.workEventCounter);
personalEventCounter = itemView.findViewById(R.id.personalEventCounter);
}
}
public void setItemCount(int newItemCount){
itemCount = newItemCount;
}
//sets the dayStr arrays and the dayNum array using CalendarArrayList
// to pull the day in the month and the string value(monday,tuesday,etc.)
private void setDayStrNDayNum(){
Iterator<Calendar> itr = this.calendarArrayList.iterator();
ArrayList<String> tempDayNum = new ArrayList<>();
ArrayList<String> tempDayStr = new ArrayList<>();
int i = 0;
while(itr.hasNext()){
String dayInMonth = getDayInMonth(calendarArrayList.get(i));
String weekDayToString = weekDayToString(calendarArrayList.get(i));
tempDayNum.add(dayInMonth);
tempDayStr.add(weekDayToString);
i++;
itr.next();
}//while
this.dayNum = tempDayNum;
this.dayStr = tempDayStr;
}
//takes in a Calendar Obj, gets the int, and returns it in a String Format
private String getDayInMonth (Calendar c){
Integer temp = c.get(Calendar.DAY_OF_MONTH);
String answer = Integer.toString(temp);
return answer;
}
//takes in a Calendar Obj, gets the weekday digit from 1 to 7, and returns a String
// 1 being Su for Sunday, 2 Mo for Monday, and etc.
private String weekDayToString (Calendar x){
int temp = x.get(Calendar.DAY_OF_WEEK);
switch(temp){
case 1:
return "Su";
case 2:
return "Mo";
case 3:
return "Tu";
case 4:
return "We";
case 5:
return "Th";
case 6:
return "Fr";
case 7:
return "Sa";
}
return "null";
}//weekDayToString
}