When I am in last Item In CardStackView? - java

I have RecyclerView(CardStackView) With 60 items.
Now After finish All Items .. I have Blank Page .. I do not want to Show The blank Page if all items finished ... I want to Intent to Another Activity You can see The blank Page Here
when I implement CardStackListener I Added Those Method too Like This .I want to When All card Answered Intent To ResultActivity...Like This After 60th question I want InstedOf Blank Page Intent To ResultActivity
//Card Method
#Override
public void onCardDragging(Direction direction, float ratio) {
Log.d("CardStackView", "onCardDragging: d = " + direction.name() + ", r = " + ratio);
}
#Override
public void onCardSwiped(Direction direction) {
Log.d("CardStackView", "onCardSwiped: p = " + manager.getTopPosition() + ", d = " + direction);
if (manager.getTopPosition() == mbtiQuestAdapter.getItemCount() - 5) {
mbtiQuestAdapter.addQuestion(questions);
mbtiQuestAdapter.notifyDataSetChanged();
}
position++;
Intent intent = new Intent(MbtiQuestionActivity.this, ResultActivity.class);
intent.putExtra(RESULT, result);
Log.i(TAG, "onResultClick: " + result);
startActivity(intent);
}
#Override
public void onCardRewound() {
Log.d("CardStackView", "onCardRewound: " + manager.getTopPosition());
}
#Override
public void onCardCanceled() {
Log.d("CardStackView", "onCardCanceled:" + manager.getTopPosition());
}
Adapter.java
public class MbtiQuestAdapter extends RecyclerView.Adapter<MbtiQuestAdapter.MbtiQuestViewHolder> {
private List<Question> questionList;
private LayoutInflater layoutInflater;
private final OnItemClickListener listener;
private static final String TAG = "MbtiQuestAdapter";
public interface OnItemClickListener {
void onItemClick(int position, char value);
}
public MbtiQuestAdapter(List<Question> questionList, OnItemClickListener listener) {
this.questionList = questionList;
this.listener = listener;
}
#NonNull
#Override
public MbtiQuestViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (layoutInflater == null) {
layoutInflater = LayoutInflater.from(parent.getContext());
}
MbtiItemRowBinding binding = DataBindingUtil.inflate(layoutInflater,
R.layout.mbti_item_row, parent, false);
return new MbtiQuestViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull final MbtiQuestViewHolder holder, final int position) {
final Question question = questionList.get(position);
holder.binding.txtQuesNum.setText(String.valueOf(position + 1));
holder.binding.txtQuesTitle.setText(question.getQuestion());
holder.binding.firstQues.setText(question.getAnswers().get(0).getAnswer());
holder.binding.secondQues.setText(question.getAnswers().get(1).getAnswer());
holder.binding.firstQues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(position, question.getAnswers().get(0).getValue());
}
});
holder.binding.secondQues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(position, question.getAnswers().get(1).getValue());
}
});
holder.binding.setQuestion(question);
}
#Override
public int getItemCount() {
Log.i(TAG, " List Size : " + questionList.size());
return questionList.size();
}
class MbtiQuestViewHolder extends RecyclerView.ViewHolder {
private MbtiItemRowBinding binding;
MbtiQuestViewHolder(MbtiItemRowBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
public void addQuestion(List<Question> questions) {
this.questionList.addAll(questions);
}
}
SetUp CardStackView In Activity
//Swipe RecyclerView with CardStackView
cardStackView = binding.cardStackView;
manager = new CardStackLayoutManager(this);
mbtiQuestAdapter = new MbtiQuestAdapter(questions, this);
cardStackView.setLayoutManager(manager);
cardStackView.setAdapter(mbtiQuestAdapter);
I want to Say If The items Finished Do SomeThing (Show Dialog or etc.)
Thank Guys

Working Code
private CardStackView cardStackView;
private CardStackLayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//
layoutManager = new CardStackLayoutManager(getApplicationContext(), this);
cardStackView.setLayoutManager(layoutManager);
//
}
#Override
public void onCardSwiped(Direction direction) {
if (layoutManager.getTopPosition() == adapter.getItemCount()) {
// -------------------- last position reached, do something ---------------------
startActivity(new Intent(this, MainActivity.class));
}
}
You have CardStackLayoutManager. When card is swiped, callback comes in onCardSwiped.
Here you will get top position (position displayed on top), and total item count.
If top_position == total_item_count, then it is last position, now you can do anything.
Below is Output or same

Use position to check if you have arrived to last item. Inside onBindViewHolder method
if( position+ 1 == questionList.size()){
// you are at the last item
}

You ca try this by using scrollChangeListener like :
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
LinearLayoutManager layoutManager=LinearLayoutManager.class.cast(recyclerView.getLayoutManager());
int totalItemCount = layoutManager.getItemCount();
int lastVisible = layoutManager.findLastVisibleItemPosition();
boolean endHasBeenReached = lastVisible + 5 >= totalItemCount;
if (totalItemCount > 0 && endHasBeenReached) {
//you have reached to the bottom of your recycler view
}
}
});

Some code correction, it is better not to create listeners in onBindViewHolder() because it will be set each time this method called, better to set ones in ViewHolder
For example :
Override
public void onBindViewHolder(#NonNull final MbtiQuestViewHolder holder, final int position) {
holder.bind(questionList.get(position))
}
class MbtiQuestViewHolder extends RecyclerView.ViewHolder {
private MbtiItemRowBinding binding;
MbtiQuestViewHolder(MbtiItemRowBinding binding) {
super(binding.getRoot());
this.binding = binding;
binding.firstQues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(getAdapterPosition(), questionList.get(getAdapterPosition()).getAnswers().get(0).getValue());
}
});
binding.secondQues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(getAdapterPosition(), questionList.get(getAdapterPosition()).getAnswers().get(1).getValue());
}
});
}
public void bind(Question question){
binding.txtQuesNum.setText(String.valueOf(position + 1));
binding.txtQuesTitle.setText(question.getQuestion());
binding.firstQues.setText(question.getAnswers().get(0).getAnswer());
binding.secondQues.setText(question.getAnswers().get(1).getAnswer());
binding.setQuestion(question);
}
public void addQuestion(List<Question> questions) {
this.questionList.addAll(questions);
}
}

you could compare with CardStackLayoutManager.getTopPosition(), which should be the index position currently displayed. the CardStackView GitHub explains the methods which are available.
alternatively, just count the number of swipes:
int currentPosition = 0;
#Override
public void onCardSwiped(Direction direction) {
currentPosition++;
}

//define the layoutmanager
private CardStackLayoutManager manager;
//make CardStackListener in layout manger and u need to implement methods
manager = new CardStackLayoutManager(this, new CardStackListener() {
#Override
public void onCardDragging(Direction direction, float ratio) {
}
#Override
public void onCardSwiped(Direction direction) {
}
#Override
public void onCardRewound() {
}
#Override
public void onCardCanceled() {
}
#Override
public void onCardAppeared(View view, int position) {
//here if u print position you will find the position of your viewed item and this function will call when card viewed
}
#Override
public void onCardDisappeared(View view, int position) {
Log.d("onCardDisappeared: ", "" + position);
//here if u print position you will find the position of your Disappeared item and this function will call when card disappear
}
}
});
cardStackView.setLayoutManager(manager);
cardStackView.setAdapter(cardStackAdapter);

Related

Transition between 2 recycler views having cards

I have 2 recycler views that have cards.They basically look the same have the same number of cards and everthing. The first one is for like viewing and other stuff and the second one is only for deleting cards. OnlongClicking a card in the first recycler view triggers the opening of the second recycler view. I wanted to add transitions in between them like what keep notes has done when a card is long clicked. Both the recycler view use the same adapter. I have set what the adapter should do based on passing context to the adapter. enter image description here this is my 1st layout having the 1st recycler view.enter image description here this is the 2nd layout having the second recycler view.I want like a seamless transition for the tool bar again just like what Google keeps has done.A simple solution would be preferred as I am very new to this stuff.
Here is the java code for the adapter.
public class Task_recycle_view_adapter extends RecyclerView.Adapter<Task_recycle_view_adapter.ViewHolder>{
private List<struct_task> task_list= new ArrayList<>();
private ArrayList<String> isSelected=new ArrayList<String>();
protected Context context1;
protected Context context2;
private String labelName;
private String taskName;
private ConstraintLayout label_menu_avatar;
public Task_recycle_view_adapter(Context context1,Context context2)
{
this.context1=context1;
this.context2=context2;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {//parent is the parent of the recycle view it is taken as an arg to use it to attach the every view to the parent view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_task,parent,false);//to inflate a layout
ViewHolder holder= new ViewHolder(view);
return holder;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.taskname.setText(task_list.get(position).getTask_name());
holder.taskid.setText(String.valueOf(task_list.get(position).getTask_id()));
if(context2==null && context1!=null) {
String taskName=task_list.get(position).getTask_name();
Long taskid=task_list.get(position).getTask_id();
String duedate=task_list.get(position).getDue_date();
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(context1);
ArrayList<SubTaskModel> subtask_list=(ArrayList<SubTaskModel>) dataBaseHelper.getAllSubTasksFor(labelName, Long.parseLong(holder.taskid.getText().toString()));
Intent intent1 =new Intent(context1,ViewTaskActivity.class);
intent1.putExtra("label_name",labelName);
intent1.putExtra("task_id",taskid);
intent1.putExtra("task_name",taskName);
intent1.putExtra("due_date",duedate);
intent1.putParcelableArrayListExtra("subtask_list", (ArrayList<? extends Parcelable>) subtask_list);
context1.startActivity(intent1);
}
});
holder.parent.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent intent2 = new Intent(context1, Delete_page_Activity.class);
intent2.putParcelableArrayListExtra("task_list", (ArrayList<? extends Parcelable>) task_list);
intent2.putExtra("label_name",labelName);
intent2.putExtra("selected_task",taskName);
Pair[] pairs = new Pair[1];
pairs[0]= new Pair<View,String>(label_menu_avatar,"transition1");
ActivityOptions options= ActivityOptions.makeSceneTransitionAnimation((Activity) context1,pairs);
context1.startActivity(intent2,options.toBundle());
return true;
}
});
}
if(context2!=null && context1==null)
{
if(taskName.equals(task_list.get(position).getTask_name()))
{
holder.active=1;
isSelected.add(holder.taskid.getText().toString());
holder.parent.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
}
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.active==0) {
isSelected.add(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card);
holder.active=1;
}
else {
isSelected.remove(holder.taskid.getText().toString());
v.findViewById(R.id.layout_for_every_task).setBackgroundResource(R.drawable.background_for_task_card_transparent);
holder.active=0;
}
}
});
}
// subtasks 1 to 5
if(task_list.get(position).getSubtask1()!=null)
holder.subtask1.setText(task_list.get(position).getSubtask1());
else
holder.subtask1.setVisibility(View.GONE);
if(task_list.get(position).getSubtask2()!=null)
holder.subtask2.setText(task_list.get(position).getSubtask2());
else
holder.subtask2.setVisibility(View.GONE);
if(task_list.get(position).getSubtask3()!=null)
holder.subtask3.setText(task_list.get(position).getSubtask3());
else
holder.subtask3.setVisibility(View.GONE);
if(task_list.get(position).getSubtask4()!=null)
holder.subtask4.setText(task_list.get(position).getSubtask4());
else
holder.subtask4.setVisibility(View.GONE);
if(task_list.get(position).getSubtask5()!=null)
holder.subtask5.setText(task_list.get(position).getSubtask5());
else
holder.subtask5.setVisibility(View.GONE);
// due date
if(task_list.get(position).getDue_date()!=null)
holder.duedate.setText(task_list.get(position).getDue_date());
else
holder.duedate.setVisibility(View.GONE);
// progress
holder.progresscircle.setProgress(task_list.get(position).getProgress());
}
#Override
public int getItemCount() {
return task_list.size();
}
public void setTask_list(List<struct_task> task_list) {
this.task_list = task_list;//to refresh the data inside the recycler view
}
#Override
public int getItemViewType(int position) {
return position;
}
public String getLabelName() {
return labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public ArrayList<String> getIsSelected() {
return isSelected;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public void setLabel_menu_avatar(ConstraintLayout label_menu_avatar) {
this.label_menu_avatar = label_menu_avatar;
}
public static class ViewHolder extends RecyclerView.ViewHolder{// holds the view for every item inside the recycle view
private TextView taskname,taskid,duedate,subtask1,subtask2,subtask3,subtask4,subtask5;
private CardView parent;
private ProgressBar progresscircle;
public void setActive(int active) {
this.active = active;
}
private int active;
public ViewHolder(#NonNull View itemView) {
super(itemView);
taskid=itemView.findViewById(R.id.task_id);
taskname = itemView.findViewById(R.id.task_name);
parent = itemView.findViewById(R.id.card_for_every_task);
duedate = itemView.findViewById(R.id.due_date);
progresscircle = itemView.findViewById(R.id.progress_circular);
subtask1 = itemView.findViewById(R.id.subtask_1);
subtask2 = itemView.findViewById(R.id.subtask_2);
subtask3 = itemView.findViewById(R.id.subtask_3);
subtask4 = itemView.findViewById(R.id.subtask_4);
subtask5 = itemView.findViewById(R.id.subtask_5);
active=0;
}
}
}
Here is the code for the 1st activity i.e the 1st image:
public class TaskPageActivity extends AppCompatActivity {
private RecyclerView task_rv;//task recycler view
private FloatingActionButton addTask;
private long tasksNum;
private String labelName;
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private Task_recycle_view_adapter adapter= new Task_recycle_view_adapter(this,null);
private List<struct_task> tasks;
private EditText searchBar;
private ConstraintLayout search_btn;
private ConstraintLayout calendar_btn;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_title);
getWindow().getSharedElementExitTransition();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
search_btn= findViewById(R.id.search_btn);
calendar_btn=findViewById(R.id.calendar_btn);
search_btn.setClickable(true);
search_btn.setFocusable(true);
labelName = getIntent().getExtras().getString("832715");
TextView txtLabelName = findViewById(R.id.Label_name);
txtLabelName.setText(labelName);
task_rv = findViewById(R.id.Recycle_view_task);
addTask = findViewById(R.id.add_task);
searchBar= (SearchBar) findViewById(R.id.search_bar);
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter); //displays all tasks and return number of tasks
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
addTask.setOnClickListener(view -> {
tasksNum = getTasksNum(labelName, dataBaseHelper, adapter);
Intent intent = new Intent(TaskPageActivity.this, AddTaskPageActivity.class);
intent.putExtra("labelName", labelName);
intent.putExtra("taskID", tasksNum);
startActivity(intent);
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(searchBar.getVisibility()==View.INVISIBLE) {
search_btn.setAlpha(.5f);
searchBar.setVisibility(View.VISIBLE);
searchBar.requestFocus();
imm.showSoftInput(searchBar,InputMethodManager.SHOW_IMPLICIT);
ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
searchBar.requestFocus();
}
else {
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
}
});
searchBar.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
if(params.verticalBias==.9f) {
searchBar.requestFocus();
params.verticalBias = .55f;
searchBar.setLayoutParams(params);
}
searchBar.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if((event.getAction()==KeyEvent.ACTION_DOWN) && (keyCode==KeyEvent.KEYCODE_ENTER) && params.verticalBias==.55f)
{
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
imm.hideSoftInputFromWindow(searchBar.getWindowToken(),0);
}
return false;
}
});
}
}
});
searchBar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
AlertDialog alertDialog = new AlertDialog.Builder(TaskPageActivity.this).create();
calendar_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(calendar_btn.getAlpha()==1.0f) {
calendar_btn.setAlpha(.5f);
LayoutInflater inflater = getLayoutInflater();
View view1 = inflater.inflate(R.layout.dialog_calendar,null);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.setView(view1);
CalendarView mCalendarView= view1.findViewById(R.id.calendar);
mCalendarView.setMinDate(Calendar.getInstance().getTimeInMillis());
alertDialog.show();
}
}
});
alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(calendar_btn.getAlpha()==.5f)
calendar_btn.setAlpha(1.0f);
}
});
}
private void filter(String string) {
ArrayList<struct_task> filteredList = new ArrayList<>();
for(struct_task item: tasks)
{
if(item.getTask_name().contains(string) || item.getTask_name().contains(string.toUpperCase()))
{
filteredList.add(item);
}
}
if(filteredList.size()!=0) {
adapter.setTask_list(filteredList);
task_rv.setAdapter(adapter);
}
}
#Override
public void onBackPressed() {
if(searchBar.getText().toString().length()!=0) {
showAllTasks(labelName, dataBaseHelper, adapter);
searchBar.setText(null);
searchBar.setVisibility(View.INVISIBLE);
search_btn.setAlpha(1.0f);
}
else if(searchBar.getText().toString().length()==0)
{
super.onBackPressed();
}
}
#Override
protected void onResume() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
showAllTasks(labelName, dataBaseHelper, adapter);
if(params.verticalBias==.54f) {
searchBar.requestFocus();
params.verticalBias = .9f;
searchBar.setLayoutParams(params);
searchBar.clearFocus();
}
if(searchBar.getText().toString().length()==0) {
showAllTasks(labelName, dataBaseHelper, adapter);
}
else {
filter(searchBar.getText().toString());
}
super.onResume();
}
private void showAllTasks(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
tasks = dataBaseHelper.getAllTasksFor(labelName);
adapter.setLabelName(labelName);
adapter.setTask_list(tasks);
task_rv.setAdapter(adapter);
task_rv.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
}
long getTasksNum(String labelName, DataBaseHelper dataBaseHelper, Task_recycle_view_adapter adapter) {
return dataBaseHelper.getLastTaskID(labelName)+1; //to determine ID of next task
}
#Override
protected void onUserLeaveHint() {
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) searchBar.getLayoutParams();
params.verticalBias=.9f;
searchBar.setLayoutParams(params);
searchBar.setText(null);
searchBar.clearFocus();
super.onUserLeaveHint();
}
}
And finally for the 2nd activity which is triggered by longclicking any card
public class Delete_page_Activity extends AppCompatActivity {
private Task_recycle_view_adapter recycle_view_adapter = new Task_recycle_view_adapter(null,this);
private ArrayList<String> delete_list=new ArrayList<>();
private DataBaseHelper dataBaseHelper = new DataBaseHelper(this);
private String labelName=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_page);
overridePendingTransition(0,0);
Toolbar toolbar=findViewById(R.id.toolbar_bar);
ImageView close_btn=findViewById(R.id.close_btn);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
ArrayList<struct_task> task_list = getIntent().getParcelableArrayListExtra("task_list");
labelName=getIntent().getExtras().getString("label_name");
String task = getIntent().getExtras().getString("selected_task");
Log.e("test",labelName);
RecyclerView recyclerView = findViewById(R.id.delete_Recycler_View);
recycle_view_adapter.setTaskName(task);
recycle_view_adapter.setTask_list(task_list);
recyclerView.setAdapter(recycle_view_adapter);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
close_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.tool_bar_item1:
delete_list = recycle_view_adapter.getIsSelected();
if(delete_list.size()==0)
{
Toast toast1= new Toast(this);
toast1.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg1,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast1.setView(view);
toast1.show();
}
else {
for (int task = 0; task < delete_list.size(); task++) {
dataBaseHelper.deleteOneTask(labelName, Long.parseLong(delete_list.get(task)));
}
finish();
}
break;
case R.id.tool_bar_item2:
Boolean flag=dataBaseHelper.deleteAllCompletedTasks(labelName);
if(flag)
finish();
else
{
Toast toast2= new Toast(this);
toast2.setDuration(Toast.LENGTH_SHORT);
LayoutInflater inflater= (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.activity_toast_msg2,null);
view.setBackgroundResource(R.drawable.background_for_calendar);
toast2.setView(view);
toast2.show();
}
break;
}
return true;
}
}
I have added the code related to the scene transititon which is in the adapter.
here is a gif of the problem when i add a scene transition
enter image description here
As u can see there are 2 pauses when going from 1st to 2nd activity 1st pause being longer 2nd one shorter. And also a pause when exiting the 2nd activity which seems to have the same duration as the 2nd pause.

Recycleview cardview Onclick duplicate effects when scrolling

I'm making my first app (calendar),
clicking the cardview item applies the same effect (changing Textview text color and Imageview background) to other items when scrolling the recycleview
in the main activity
RecyclerView daysRecyclerView;
DaysAdapter daysAdapter;
private RecyclerView.LayoutManager horizontalLayout;
ArrayList<DaysModel> daysModels;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
daysModels = getDaysList();
initDaysRecycleview();
}
private void initDaysRecycleview(){
daysRecyclerView = findViewById(R.id.daysRecyclerView);
daysRecyclerView.setHasFixedSize(true);
horizontalLayout = new LinearLayoutManager(this,RecyclerView.HORIZONTAL,false);
daysAdapter = new DaysAdapter(daysModels);
daysRecyclerView.setLayoutManager(horizontalLayout);
daysRecyclerView.setAdapter(daysAdapter);
daysAdapter.setOnItemClickListener(new DaysAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
dayClickHandler(position, 1);
}
});
}
public void dayClickHandler(int position, int change){
daysModels.get(position).changeDayHighlight(change);
daysAdapter.notifyItemChanged(position);
}
private ArrayList<DaysModel> getDaysList(){
//Not accurate used for testing
ArrayList<DaysModel> models = new ArrayList<DaysModel>();
String[] dayName ={"SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON"};
int i,j;
for (i = 0;i <dayName.length;i++){
j =i+1;
models.add(new DaysModel(dayName[i], j, 0, false));
}
return models;
}
I'm using an interface for the onClickListener.
ViewHolder
public class DaysViewHolder extends RecyclerView.ViewHolder {
TextView hDayName,hDayNumber;
ImageView currentDayHighlight;
CardView dayCard;
public DaysViewHolder(View itemView, DaysAdapter.OnItemClickListener listener) {
super(itemView);
this.hDayName = itemView.findViewById(R.id.dayName);
this.hDayNumber = itemView.findViewById(R.id.dayNumber);
this.currentDayHighlight = itemView.findViewById(R.id.dayHihlight);
this.dayCard = itemView.findViewById(R.id.dayCard);
dayCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
Adapter
public class DaysAdapter extends RecyclerView.Adapter<DaysViewHolder> {
Context context;
ArrayList<DaysModel> daysModels;
OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public DaysAdapter(ArrayList<DaysModel> daysModels) {
this.daysModels = daysModels;
}
#NonNull
#Override
public DaysViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.day_card,parent,false);
DaysViewHolder daysViewHolder = new DaysViewHolder(view, mListener);
return daysViewHolder;
}
#Override
public void onBindViewHolder(#NonNull DaysViewHolder holder, int position) {
DaysModel currentItem = daysModels.get(position);
holder.hDayName.setText(currentItem.getDayName());
holder.hDayNumber.setText(String.valueOf(currentItem.getDayNumber()));
if(currentItem.isDayHighlighted() == 1){
holder.currentDayHighlight.setBackgroundResource(R.drawable.tiny_background);
holder.hDayNumber.setTextColor(Color.BLACK);
}
}
#Override
public int getItemCount() {
return daysModels.size();
}
}
sorry for the long code text, I've just started and I am already struggling.
All you need is to set else part for you if condition in bind method of Adapter class.
So change your bind method to something like this:
#Override
public void onBindViewHolder(#NonNull DaysViewHolder holder, int position) {
DaysModel currentItem = daysModels.get(position);
holder.hDayName.setText(currentItem.getDayName());
holder.hDayNumber.setText(String.valueOf(currentItem.getDayNumber()));
if(currentItem.isDayHighlighted() == 1){
holder.currentDayHighlight.setBackgroundResource(R.drawable.tiny_background);
holder.hDayNumber.setTextColor(Color.BLACK);
}else{
holder.currentDayHighlight.setBackgroundResource(/*what ever you want for default situation*/);
holder.hDayNumber.setTextColor(/* for example Color.White*/);
}
}

Recycler ItemClick doesn't work with Countdown timer

I'm trying to develop Letters and Numbers(Countdown) like game. In this concept, user should able to use the arithmetic operations results of given numbers once for the reach goal number in a given time.
I'm using the Recyclerview to show and list the steps of calculation but while Countdown Timer ticking, I can't click the items of recyclerview. It only works when the Countdown Timer finished up.
Please help me to find out the problem.
Here is what I mean as a image: https://hizliresim.com/zWThaa
Here is my adapter
public interface OnItemListener{
void onItemClick(int position);
}
private OnItemListener mOnItemListener;
private ArrayList<String> n1;
private ArrayList<String> n2;
private ArrayList<String> res;
private ArrayList<String> op;
public NotesRecyclerAdapter(ArrayList<String> n1, ArrayList<String> n2, ArrayList<String> res, ArrayList<String> op, OnItemListener onItemListener) {
this.n1 = n1;
this.n2 = n2;
this.res = res;
this.op = op;
this.mOnItemListener = onItemListener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item, parent, false);
return new ViewHolder(view, mOnItemListener);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
if(n2.size() <= position ){
holder.second.setText(" ");
}
else{
holder.second.setText(n2.get(position));
}
if(op.size() <= position){
holder.operation.setText(" ");
}
else{
holder.operation.setText(op.get(position));
}
if (res.size() <= position){
holder.result.setText(" ");
}
else {
holder.result.setText(res.get(position));
}
holder.first.setText(n1.get(position));
}
#Override
public int getItemCount() {
return n1.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView first;
TextView operation;
TextView second;
TextView result;
OnItemListener mOnItemListener;
public ViewHolder(View itemView, OnItemListener onItemListener) {
super(itemView);
first = itemView.findViewById(R.id.first);
operation = itemView.findViewById(R.id.op);
second = itemView.findViewById(R.id.secondNum);
result = itemView.findViewById(R.id.res);
this.mOnItemListener = onItemListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mOnItemListener.onItemClick(getAdapterPosition());
}
}
}
Here is Activity,
public class CalculateActivity extends AppCompatActivity implements Adapter.OnItemListener{
RecyclerView rView;
Adapter adapter;
.//Other definitions etc.
.
protected void onCreate(Bundle savedInstanceState) {
. . . // Other
adapter = new Adapter(firstNumbers,secondNumbers,operationResults,operators,this);
rView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rView.setAdapter(adapter);
new CountDownTimer(45000, 1) {
#Override
public void onTick(long millisUntilFinished) {
// Calculation step
}
#Override
public void onFinish() {
}
}.start();
...//Button Listeneres etc...
} // end of onCreate
#Override
public void onItemClick(int position) {
System.out.println(position + " Clicked!");
View view = rView.getChildAt(position);
TextView res = view.findViewById(R.id.res);
moveCount++;
if(moveCount % 2 == 0){
firstNumbers.add((String)res.getText()); //res is textview of the operation results.
}
else{
secondNumbers.add((String)res.getText());
}
view.setClickable(false)
dataChange(); //just notifyDataSetChange
}
PS: I also used this method. I can able to click with this method but it returns wrong value of item's position while Countdown Timer ticking. Just like I explained above, it works perfectly when the timer runs out.
Probably you have a problem with adapter...
I don't know what you do in the onTick method, whether you block something or...
I'm not sure what do you want but consider whether it is possible to do so
You can create Step class like
public class Step {
private String first;
private String operation;
private String second;
private String result;
private boolean disabled; //instead view clickable
//TODO generate getters and setters
}
Try this adapter
public class NotesRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final OnItemListener mOnItemListener;
private final List<Step> items;
public NotesRecyclerAdapter(List<Step> items, OnItemListener onItemListener) {
this.items = items;
this.mOnItemListener = onItemListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_item, parent, false);
return new NotesViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
NotesViewHolder mHolder = (NotesViewHolder) holder;
Step item = items.get(position);
mHolder.first.setText(item.getFirst());
if(items.size() <= position){ // Im not sure why this
mHolder.second.setText(" ");
mHolder.operation.setText(" ");
mHolder.result.setText(" ");
}else{
mHolder.second.setText(item.getSecond());
mHolder.operation.setText(item.getOperation());
mHolder.result.setText(item.getResult());
}
if(mOnItemListener != null){
mHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mOnItemListener.onItemClick(mHolder.getAdapterPosition());
}
});
}
}
#Override
public int getItemCount() {
return items.size();
}
public Step getItem(int position) {
if(this.items == null || position < 0 || position >= this.items.size()) return null;
return this.items.get(position);
}
public interface OnItemListener{
void onItemClick(int position);
}
public static class NotesViewHolder extends RecyclerView.ViewHolder {
public TextView first;
public TextView operation;
public TextView second;
public TextView result;
public NotesViewHolder(View itemView) {
super(itemView);
first = itemView.findViewById(R.id.first);
operation = itemView.findViewById(R.id.op);
second = itemView.findViewById(R.id.secondNum);
result = itemView.findViewById(R.id.res);
}
}
}
and onClick method
#Override
public void onItemClick(int position) {
Toast.makeText(this, "Clicked: "+ position, Toast.LENGTH_SHORT).show();
Step step = adapter.getItem(position);
if(step != null){
if(step.isDisabled()){
Toast.makeText(this, "Disabled"+ position, Toast.LENGTH_SHORT).show();
return;
}
moveCount++;
if(moveCount % 2 == 0){
step.setFirst(random number or what); //how do you get number, randomly or...
} else{
step.setSecond(random number or what);
}
step.setDisabled(false); //instead view.setClickable(false)
dataChange(); //just notifyDataSetChange
}
}

ExpandableRecyclerView - How to expand and collapse multiple CardViews simultaneously

Is it possible to expand and collapse multiple CardViews within a RecyclerView at the same time? I created a header (for my RecyclerView) with two buttons but I'm not sure what needs to go in the click event.
RecyclerView adapter class
public class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
public boolean isSupposedToBeCollapsed;
private Context mContext;
RecyclerViewHeader header;
List<RecyclerViewItem> listItems;
ValueAnimator mAnimator;
public MyRecyclerAdapter(Context context, RecyclerViewHeader header, List<RecyclerViewItem> listItems)
{
this.mContext = context;
this.header = header;
this.listItems = listItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_HEADER)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_header, parent, false);
return new MyRecyclerAdapter.VHHeader(v);
}
else if(viewType == TYPE_ITEM)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
return new MyRecyclerAdapter.VHItem(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
private RecyclerViewItem getItem(int position)
{
return listItems.get(position);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Typeface iconFont = FontManager.getTypeface(mContext, FontManager.FONTAWESOME);
if (holder instanceof VHHeader)
{
final VHHeader vhHeader = (VHHeader)holder;
vhHeader.btnExpandAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isSupposedToBeCollapsed){
// change visibility to 'VISIBLE'
txtB.setVisibility(View.VISIBLE);
// change direction of chevron to 'up'
txtExpandCollapse.setText(R.string.fa_icon_chevron_up);
// apply animation to the height of 'txtB'
mAnimator = slideAnimator(0, textBHeight);
// start the animation
mAnimator.start();
}
else{
}
}
});
vhHeader.btnCollapseAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isSupposedToBeCollapsed){
// change visibility to 'VISIBLE'
txtB.setVisibility(View.VISIBLE);
// change direction of chevron to 'up'
txtExpandCollapse.setText(R.string.fa_icon_chevron_up);
// apply animation to the height of 'txtB'
mAnimator = slideAnimator(0, textBHeight);
// start the animation
mAnimator.start();
}
else{
}
}
});
}
else if (holder instanceof VHItem)
{
RecyclerViewItem currentItem = getItem(position-1);
final VHItem vhItem = (VHItem)holder;
vhItem.txtA.setText(currentItem.getTitle());
vhItem.txtB.setText(currentItem.getDescription());
vhItem.txtB.setVisibility(View.GONE);
vhItem.txtExpandCollapse.setText(R.string.fa_icon_chevron_down);
vhItem.txtExpandCollapse.setTypeface(iconFont);
//Add onPreDrawListener
vhItem.txtB.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
vhItem.txtB.getViewTreeObserver().removeOnPreDrawListener(this);
vhItem.txtB.setVisibility(View.GONE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
vhItem.txtB.measure(widthSpec, heightSpec);
vhItem.textBHeight = vhItem.txtB.getMeasuredHeight();
return true;
}
});
vhItem.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(vhItem.txtB.getVisibility() == View.GONE){
vhItem.expand();
} else {
vhItem.collapse();
}
}
});
vhItem.mLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(vhItem.txtB.getVisibility() == View.GONE){
vhItem.expand();
} else {
vhItem.collapse();
}
}
});
vhItem.txtExpandCollapse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(vhItem.txtB.getVisibility() == View.GONE){
vhItem.expand();
} else {
vhItem.collapse();
}
}
});
}
}
// need to override this method
#Override
public int getItemViewType(int position) {
if(isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position)
{
return position == 0;
}
// increasing getItemcount to 1. This will be the row of header.
#Override
public int getItemCount() {
return listItems.size()+1;
}
class VHHeader extends RecyclerView.ViewHolder{
Button btnCollapseAll, btnExpandAll;
public VHHeader(View headerView) {
super(headerView);
this.btnCollapseAll = headerView.findViewById(R.id.btn_collapseall);
this.btnExpandAll = headerView.findViewById(R.id.btn_expandall);
}
}
public class VHItem extends RecyclerView.ViewHolder{
CardView cardView;
LinearLayout mLinearLayout;
RecyclerView mRecyclerView;
RelativeLayout mRelativeLayout;
TextView txtExpandCollapse, txtA, txtB;
public int textBHeight;
public VHItem(View itemView) {
super(itemView);
this.cardView = itemView.findViewById(R.id.cv);
this.mLinearLayout = itemView.findViewById(R.id.cardview_tconnections_titlerow);
this.mRelativeLayout = itemView.findViewById(R.id.my_relativelayout);
this.mRecyclerView = itemView.findViewById(R.id.my_recyclerview);
this.txtExpandCollapse = itemView.findViewById(R.id.tv_expandcollapse);
this.txtA = itemView.findViewById(R.id.tv_A);
this.txtB = itemView.findViewById(R.id.tv_B);
}
private void expand() {
// change visibility to 'VISIBLE'
txtB.setVisibility(View.VISIBLE);
// change direction of chevron to 'up'
txtExpandCollapse.setText(R.string.fa_icon_chevron_up);
// apply animation to the height of 'txtB'
mAnimator = slideAnimator(0, textBHeight);
// start the animation
mAnimator.start();
}
private void collapse() {
// change direction of chevron to 'down'
txtExpandCollapse.setText(R.string.fa_icon_chevron_down);
int finalHeight = txtB.getHeight();
ValueAnimator mAnimator = slideAnimator(finalHeight, 0);
mAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
txtB.setVisibility(View.GONE);
}
#Override
public void onAnimationStart(Animator animator) {
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
mAnimator.start();
}
public ValueAnimator slideAnimator(int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
// update height
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = txtB.getLayoutParams();
layoutParams.height = value;
txtB.setLayoutParams(layoutParams);
}
});
return animator;
}
}
}
Fragment class
public class MyFragment extends android.support.v4.app.Fragment {
private MyRecyclerAdapter adapter;
public MyFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_rv, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
View v = getView();
assert v != null;
recyclerView = v.findViewById(R.id.my_recyclerview);
linearLayoutManager = new LinearLayoutManager(getActivity());
MyRecyclerAdapter adapter = new MyRecyclerAdapter(getContext(), getHeader(), getListItems());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
super.onActivityCreated(savedInstanceState);
}
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
public RecyclerViewHeader getHeader()
{
return new RecyclerViewHeader();
}
public List<RecyclerViewItem> getListItems()
{
List<RecyclerViewItem> rvItems = new ArrayList<>();
RecyclerViewItem itemA = new RecyclerViewItem();
itemA.setConnectionMode("Item A");
itemA.setConnectionName("Feature A1");
rvItems.add(itemA);
RecyclerViewItem itemB = new RecyclerViewItem();
itemB.setConnectionMode("Item B");
itemB.setConnectionName("Feature B1\nFeature B2");
rvItems.add(itemB);
RecyclerViewItem itemC = new RecyclerViewItem();
itemC.setConnectionMode("Item C");
itemC.setConnectionName("Feature C1\nFeature C2\nFeature C3");
rvItems.add(itemC);
return rvItems;
}
}
What you can do is, set a variable(boolean) that stores the state of the card (expanded/collapsed) in the RecyclerAdapter code.
Then, in your onBindViewHolder code block, write a piece of code to check if the card should be expanded or collapsed using the above-mentioned variable and the required display code.
Example:
if(isSuppossedToBeCollapsed){
textView.setVisibility = false;
}
else{
textView.setVisibility = true;
}
You can then call notifyDatasetChanged in your RecyclerAdapter code to update the recycler views when you click the button which will redraw the views and reflect the state of the cards(expanded/collapsed) accordingly.
NotifyDatasetChanged Documentation

How to update Datamodel in RecyclerviewAdapter

i created a recyclerview where i can see all my chats. Every item contains the name, the lastmessage and a thumb. if the user send or receive a new message, it should be displayed there and the item should go to position 0. Now i have the problem that the message is displayed, but the chat item goes only to the first position if the position was not 0 before. So if i receive two new messages its not working anymore because the data model is the same like before. So how can i fit my data model to the current position of every item. Currently my adapter looks like this:
private static final String TAG = "CustomAdapter";
private Context context;
private Activity mActivity;
private List<MatchesObject> matchesList;
private String currentUid;
public matchadapterino(Activity mActivity, ArrayList<MatchesObject> mDataSet) {
this.mActivity = mActivity;
this.matchesList = mDataSet;
}
// Create new views (invoked by the layout manager)
#Override
public matchadapterino.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
// Create a new view.
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.matchesitem, viewGroup, false);
return new matchadapterino.ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final matchadapterino.ViewHolder viewHolder, final int position) {
viewHolder.getMatchname().setText(matchesList.get(position).getUsername());
if (!matchesList.get(position).getProfileImageUrl().equals("default")) {
Picasso.with(mActivity).load(matchesList.get(position).getProfileImageUrl()).into(viewHolder.getMatchImage());
getLastMSG(matchesList.get(position).getUserId(), viewHolder.getLastMSG(), position);
viewHolder.getMatchImage().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mActivity, UserDetailView.class);
//
i.putExtra("userId", matchesList.get(position).getUserId());
mActivity.startActivity(i);
}
});
} else {
viewHolder.getMatchImage().setImageResource(R.mipmap.ic_launcher_round);
}
viewHolder.getForeground().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mActivity, Chat.class);
Bundle b = new Bundle();
b.putString("matchId", matchesList.get(position).getUserId());
i.putExtras(b);
mActivity.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return matchesList.size();
}
// Get element from your dataset at this position and replace the contents of the view
// with that element
public void removeItem(int position) {
matchesList.remove(matchesList.get(position));
notifyItemRemoved(position);
}
// Return the size of your dataset (invoked by the layout manager)
/**
* Provide a reference to the type of views that you are using (custom ViewHolder)
*/
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView matchname, lastMSG;
public ImageView matchImage;
private RelativeLayout foreground;
private RelativeLayout background;
public ViewHolder(View v) {
super(v);
currentUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
matchname = itemView.findViewById(R.id.matchname);
matchImage = itemView.findViewById(R.id.matchImages);
lastMSG = itemView.findViewById(R.id.lastmsg);
foreground = itemView.findViewById(R.id.foregroundmatch);
background = itemView.findViewById(R.id.backgroundmatch);
}
public RelativeLayout getForeground() {
return foreground;
}
public RelativeLayout getBackground() {
return background;
}
public TextView getLastMSG() {
return lastMSG;
}
public TextView getMatchname() {
return matchname;
}
public ImageView getMatchImage() {
return matchImage;
}
}
private void getLastMSG(final String userId, final TextView lastMSG, final int position) {
final String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userid).child("connections").child("matches").child(userId);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
notifyItemMoved(0, position);
Toast.makeText(mActivity, "position changed" + position, Toast.LENGTH_LONG).show();
if (dataSnapshot.child("lastMsgBy").getValue().toString().equals(userid)) {
lastMSG.setTextColor(Color.parseColor("#d2403a3a"));
String lastMsg = dataSnapshot.child("lastMsg").getValue().toString();
lastMSG.setText(lastMsg);
} else {
lastMSG.setTextColor(Color.parseColor("#000000"));
String lastMsg = dataSnapshot.child("lastMsg").getValue().toString();
lastMSG.setText(lastMsg);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}

Categories