My problem is that I have a recycler view that opens a dialog when a tap on them, but when rapidly tap on two different item it opens two dialog.
How can I solve this?.
I've tried
using a bool before the click action:
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if(!clicked[0]){
clicked[0] = true;
if (mListener != null) {
mListener.onClickBoard(mValues.get(i));
}else{
((MainActivity)mContext).onClickBoard(mValues.get(i).getAreaId(), mValues.get(i).getName());
}
}
}
})
but this just solve the case when I double tap the same item, but not when I tap different items fast.
hope you can help me, what should I do.
EDIT
I would prefer to solve it from the adapter because I will use the solution for other recycler views, and the others don't call a dialog.
My Adapter Class:
public class MyBoardAdapter extends RecyclerView.Adapter<MyBoardAdapter.ViewHolder> {
private List<Board> mValues;
private Context mContext;
private final OnBoardFragmentInteractionListener mListener;
public MyBoardAdapter(List<Board> mValues, OnBoardFragmentInteractionListener mListener, Context context) {
this.mValues = mValues;
this.mContext = context;
this.mListener = mListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_board, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int i) {
holder.mItem = mValues.get(i);
holder.tvName.setText(holder.mItem.getName());
holder.tvWaiter.setVisibility(View.GONE);
holder.tvCount.setVisibility(View.GONE);
final boolean[] clicked = {false};
GestureDetector gestureDetector;
byte[] decodedString = Base64.decode(holder.mItem.getSrc(), Base64.DEFAULT);
try {
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivTable.setImageBitmap(decodedByte);
} catch (Exception e) {
e.printStackTrace();
}
Map<String, String> map = isEmpty(holder.mItem.getAreaId(), holder.mItem.getName());
if (!map.isEmpty()) {
holder.ivTable.setImageResource(R.mipmap.ic_launcher_atento_round);
holder.tvWaiter.setText(map.get("name"));
holder.tvWaiter.setVisibility(View.VISIBLE);
holder.tvCount.setText("(" + map.get("count") + ")");
holder.tvCount.setVisibility(View.VISIBLE);
}
gestureDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener(){
});
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if(!clicked[0]){
clicked[0] = true;
if (mListener != null) {
mListener.onClickBoard(mValues.get(i));
}else{
((MainActivity)mContext).onClickBoard(mValues.get(i).getAreaId(), mValues.get(i).getName());
}
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public void setmValues(List<Board> mValues) {
this.mValues = mValues;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
#BindView(R.id.ivBoard)
ImageView ivTable;
#BindView(R.id.tvName)
TextView tvName;
#BindView(R.id.tvWaiter)
TextView tvWaiter;
#BindView(R.id.tvCount)
TextView tvCount;
public Board mItem;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
this.mView = itemView;
}
#Override
public String toString() {
return "ViewHolder{" +
"mView=" + mView +
", ivTable=" + ivTable +
", tvName=" + tvName +
", tvWaiter=" + tvWaiter +
", tvCount=" + tvCount +
", mItem=" + mItem +
'}';
}
}
public Map<String, String> isEmpty(String area, String mesa) {
Map<String, String> response = new HashMap<>();
if (!mOcu.get(0).isEmpty()) {
for (int i = 0; i <= mOcu.get(0).size() - 1; i++) {
if (mOcu.get(0).get(i).trim().equals(area.trim()) && mesa.equals(mOcu.get(1).get(i))) {
Log.i("Mesa Ocupada", mOcu.get(0).get(i) + " -- " + mOcu.get(1).get(i));
response.put("code", mOcu.get(2).get(i));
response.put("name", mOcu.get(3).get(i));
response.put("count", mOcu.get(5).get(i));
return response;
}
}
}
return response;
}
}
Dialog Code:
public void dialogCustomer() {
View mView = getLayoutInflater().inflate(R.layout.dialog_customer, null);
final AlertDialog dialog = new AlertDialog.Builder(this).setView(mView).create();
final TextView tvCustomer = (TextView) mView.findViewById(R.id.tvCustomer);
final EditText etCustomer = (EditText) mView.findViewById(R.id.etCustomer);
final Button btnSubmit = (Button) mView.findViewById(R.id.btnSubmit);
tvCustomer.setText("Atento Cliente");
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startHomeActivity(etCustomer.getText().toString());
dialog.dismiss();
}
});
etCustomer.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
startHomeActivity(etCustomer.getText().toString());
dialog.dismiss();
return true;
}
return false;
}
});
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
orderFragment = (OrderFragment) getSupportFragmentManager().findFragmentByTag("orderFragment");
if (orderFragment == null) {
new AccessBoardAsyncTask(mContext).execute("L", mBoard);
}
}
});
dialog.show();
}
If you prefer fix it from your adapter, I think you could fix it declaring a private boolean disableViews = false; in your adapter, then call notifyDataSetChanged(); after user hits a holder.mView:
if (!disableViews) {
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if (mListener != null) {
mListener.onClickBoard(mValues.get(i));
}else{
((MainActivity)mContext).onClickBoard(mValues.get(i).getAreaId(), mValues.get(i).getName());
}
disableViews = true;
notifyDataSetChanged();
}
});
} else {
holder.mView.setOnClickListener(null);
}
And then set disableViews = false; when you want to receive click events again.
Related
I am creating activity like WhatsApp to edit photos.Add text, sticker and paint on image.
when click on sendbtn only current image save not all the images.
My question is how to save all images on sendBtn click.Please help me.
Screenshot link
https://i.stack.imgur.com/Jr3ZY.jpg
Thanks in advance.
Here is my adapter.
private final List<FilePickerModel> list;
Context context;
private final String from;
private final String name;
private int pos;
private RecyclerView mediaRv;
int IMAGE_ITEM = 1;
int VIDEO_ITEM = 2;
private VideoView videoView;
private videoHolder holder;
private FilePickerActivity activity;
public MediaAdapter(List<FilePickerModel> list, Context context,RecyclerView mediaRv,String from,String name) {
this.list = list;
this.context = context;
this.mediaRv = mediaRv;
this.from = from;
this.name = name;
}
public void stopPlayer(){
if (holder.mVideoView != null){
holder.mVideoView.stopPlayback();
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == IMAGE_ITEM) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.media_item, parent, false);
return new imageHolder(view);
} else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_media_item, parent, false);
return new videoHolder(view);
}
}
#Override
public int getItemViewType(int position) {
if (list.get(position).getName().contains(".mp4")) {
return VIDEO_ITEM;
} else {
return IMAGE_ITEM;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, #SuppressLint("RecyclerView") int position) {
FilePickerModel model = list.get(position);
activity = new FilePickerActivity();
if (holder.getClass() == imageHolder.class) {
//IMAGE_ITEM
EmojiPopup popup = EmojiPopup.Builder.fromRootView(((imageHolder)holder).rootView).build(((imageHolder)holder).captionEDt);
((imageHolder)holder).emojiBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popup.toggle();
((imageHolder)holder).emojiBtn.setImageResource(R.drawable.ic_baseline_emoji_emotions_24);
}
});
if (popup.isShowing()){
((imageHolder)holder).emojiBtn.setImageResource(R.drawable.ic_baseline_emoji_emotions_24);
}else {
((imageHolder)holder).emojiBtn.setImageResource(R.drawable.ic_baseline_keyboard_24);
}
((imageHolder)holder).receiverName.setText(name);
SelectedAdapter adapter = new SelectedAdapter(list,mediaRv);
((imageHolder)holder).recyclerView.setAdapter(adapter);
((imageHolder)holder).deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int newPosition = holder.getAdapterPosition();
list.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, list.size());
adapter.notifyDataSetChanged();
}
});
try {
Uri imageUri = Uri.fromFile(model.getFile());
Bitmap bitmap = MediaStore.Images.Media.getBitmap(holder.itemView.getContext().getContentResolver(), imageUri);
((imageHolder) holder).photoEditorView.getSource().setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
((imageHolder) holder).captionEDt.setText(model.getCaption());
((imageHolder) holder).captionEDt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
model.setCaption(editable.toString());
}
});
((imageHolder) holder).mPhotoEditor = new PhotoEditor.Builder(context, ((imageHolder) holder).photoEditorView)
.setPinchTextScalable(true)
.build();
((imageHolder) holder).colorPickerView.setOnColorChangeListener(
new VerticalSlideColorPicker.OnColorChangeListener() {
#Override
public void onColorChange(int selectedColor) {
((imageHolder) holder).mSelectedColor = selectedColor;
if (((imageHolder) holder).colorPickerView.getVisibility() == View.VISIBLE) {
((imageHolder) holder).imagePhotoEditPaint.setBackgroundColor(selectedColor);
((imageHolder) holder).mPhotoEditor.setBrushColor(selectedColor);
}
}
});
((imageHolder) holder).imagePhotoEditBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((AppCompatActivity) context).finish();
}
});
((imageHolder) holder).imagePhotoEditUndo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((imageHolder) holder).mPhotoEditor.undo();
}
});
((imageHolder) holder).imagePhotoEditSticker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((imageHolder) holder).ShowBrush(false);
((imageHolder) holder).mStickerBSFragment.show(((AppCompatActivity) context).getSupportFragmentManager(), ((imageHolder) holder).mStickerBSFragment.getTag());
}
});
((imageHolder) holder).imagePhotoEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextEditorDialogFragment textEditorDialogFragment = TextEditorDialogFragment.show((AppCompatActivity) context);
textEditorDialogFragment.setOnTextEditorListener(new TextEditorDialogFragment.TextEditor() {
#Override
public void onDone(String inputText, int colorCode) {
((imageHolder) holder).mPhotoEditor.addText(inputText, colorCode);
}
});
}
});
((imageHolder) holder).imagePhotoEditPaint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (((imageHolder) holder).colorPickerView.getVisibility() == View.VISIBLE) {
((imageHolder) holder).ShowBrush(false);
} else {
((imageHolder) holder).ShowBrush(true);
}
}
});
((imageHolder) holder).sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
if (from.equals("community")) {
model.setPath(((imageHolder) holder).saveImage("/Edonomy/Public/Edonomy Images"));
} else {
model.setPath(((imageHolder) holder).saveImage("/Edonomy/Chat/Edonomy Images"));
}
intent.putExtra("media", (Serializable) list);
((MediaEditActivity) context).setResult(RESULT_OK, intent);
((MediaEditActivity) context).finish();
((MediaEditActivity)context).overridePendingTransition(android.R.anim.fade_in,
android.R.anim.fade_out);
}
});
} else {
//VIDEO_ITEM
}
}
#Override
public int getItemCount() {
return list.size();
}
static class imageHolder extends RecyclerView.ViewHolder implements StickerBSFragment.StickerListener {
private final ImageView imagePhotoEditBack;
private final ImageView imagePhotoEditUndo;
private final ImageView imagePhotoEditSticker;
private final ImageView imagePhotoEditText;
private final ImageView imagePhotoEditPaint;
private final StickerBSFragment mStickerBSFragment;
private final VerticalSlideColorPicker colorPickerView;
private final PhotoEditorView photoEditorView;
private PhotoEditor mPhotoEditor;
private int mSelectedColor;
private final EmojiEditText captionEDt;
private final ImageView sendBtn;
private final ImageView deleteBtn;
private final RecyclerView recyclerView;
private final EmojiTextView receiverName;
private final ImageView emojiBtn;
private final LinearLayout rootView;
private boolean isShown = true;
public imageHolder(#NonNull View itemView) {
super(itemView);
imagePhotoEditBack = itemView.findViewById(R.id.img_photo_edit_back);
imagePhotoEditUndo = itemView.findViewById(R.id.img_photo_edit_undo);
ImageView imagePhotoEditRedo = itemView.findViewById(R.id.img_photo_edit_redo);
ImageView imagePhotoEditCrop = itemView.findViewById(R.id.img_photo_edit_crop);
imagePhotoEditSticker = itemView.findViewById(R.id.img_photo_edit_stickers);
imagePhotoEditText = itemView.findViewById(R.id.img_photo_edit_text);
imagePhotoEditPaint = itemView.findViewById(R.id.img_photo_edit_paint);
colorPickerView = itemView.findViewById(R.id.color_picker_view);
sendBtn = itemView.findViewById(R.id.media_send_Btn);
photoEditorView = itemView.findViewById(R.id.media_photo_editor_view);
captionEDt = itemView.findViewById(R.id.media_captionBox);
recyclerView = itemView.findViewById(R.id.select_list_rv);
deleteBtn = itemView.findViewById(R.id.img_photo_delete);
receiverName = itemView.findViewById(R.id.receiver_name_tv);
emojiBtn = itemView.findViewById(R.id.emoji_media_btn);
rootView = itemView.findViewById(R.id.image_emoji_layout);
LinearLayoutManager layoutManager1 = new LinearLayoutManager(itemView.getContext());
layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager1);
mStickerBSFragment = new StickerBSFragment();
mStickerBSFragment.setStickerListener(this);
}
private void ShowBrush(boolean enableBrush) {
if (enableBrush) {
mPhotoEditor.setBrushColor(mSelectedColor);
imagePhotoEditPaint.setBackgroundColor(mSelectedColor);
mPhotoEditor.setBrushDrawingMode(true);
colorPickerView.setVisibility(View.VISIBLE);
} else {
imagePhotoEditPaint.setBackgroundColor(itemView.getContext().getResources().getColor(android.R.color.transparent));
mPhotoEditor.setBrushDrawingMode(false);
colorPickerView.setVisibility(View.INVISIBLE);
}
}
#Override
public void onStickerClick(Bitmap bitmap) {
mPhotoEditor.addImage(bitmap);
}
#SuppressLint("MissingPermission")
public String saveImage(String path) {
File folder = new File(Environment.getExternalStorageDirectory().toString() + path);
if (!folder.isDirectory()) {
folder.mkdirs();
}
File file = new File(folder
+ File.separator + ""
+ System.currentTimeMillis() + ".png");
try {
file.createNewFile();
SaveSettings saveSettings = new SaveSettings.Builder()
.setClearViewsEnabled(true)
.setTransparencyEnabled(true)
.build();
mPhotoEditor.saveAsFile(String.valueOf(file), saveSettings, new PhotoEditor.OnSaveListener() {
#Override
public void onSuccess(#NonNull String imagePath) {
// Toast.makeText(itemView.getContext(), "Image Saved Successfully", Toast.LENGTH_SHORT).show();
/**
* send result back to the ImagePickActivity
*/
}
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(itemView.getContext(), "Failed to save Image", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(itemView.getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
return String.valueOf(file);
}
}
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.
Here is a video of the behavior of the app that I am trying to explain just in case if you didn't understand my explanation of the problem. See the link below...
https://file.re/2021/09/14/2021-09-1405-16-22/
I am trying to develop an android app that has several card view layouts that will be displayed in one recycler view. I am not having much luck getting the recycler view to list the layouts like I want it to. I can add the first layout just fine, and then add the second layout just as long as the first card view layout exists in the recycler view. If it doesn't exists in the recycler view, and I try adding the second card view layout first by clicking on the button to add it a couple times, it will add it along with the first card view layout. Also, when trying to remove the card views from the layout they are not removing correctly. Here is what I have in my java code...
MainActivity.Java
public class MainActivity extends AppCompatActivity {
ArrayList<RecyclerItem> addConverterCard = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerItemAdapter recyclerItemAdapter;
private RecyclerView.LayoutManager layoutManager;
public TextView ftocConverterLabelBtn, ftokConverterLabelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_item_view);
ftocConverterLabelBtn = findViewById(R.id.add_f_to_c_converter_label_btn);
ftokConverterLabelBtn = findViewById(R.id.add_f_to_k_converter_label_btn);
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
addConverterCard.add(new RecyclerItem());
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addConverterCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
recyclerItemAdapter.notifyDataSetChanged();
closeActionButton();
}
}
});
ftokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
addConverterCard.add(new RecyclerItem());
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addConverterCard);
recyclerView.setLayoutManager(layoutManager);
recyclerItemAdapter.notifyDataSetChanged();
closeActionButton();
}
}
});
Adapter.Java
public static class RecyclerItemAdapter extends RecyclerView.Adapter<RecyclerItemAdapter.RecyclerViewHolder> {
public ArrayList<RecyclerItem> recyclerItemList;
public AdapterView.OnItemClickListener recyclerItemListener;
public List<String> converterType;
public interface OnItemClickListener {
void onItemClick (int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
recyclerItemListener = (AdapterView.OnItemClickListener) listener;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
EditText inputFahValueET;
TextView convertResult;
ImageView tempIconAndConvertBtn;
ImageView deleteCardBtn;
String shortResult, longResult;
public RecyclerViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
inputFahValueET = itemView.findViewById(R.id.input_fahrenheit_value_to_convert);
convertResult = itemView.findViewById(R.id.output_result_ftc);
tempIconAndConvertBtn = itemView.findViewById(R.id.temp_icon_convert_btn);
deleteCardBtn = itemView.findViewById(R.id.remove_card);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public static class RecyclerViewHolder2 extends RecyclerViewHolder {
EditText inputFahValueET;
TextView convertResult;
ImageView tempIconAndConvertBtn;
ImageView deleteCardBtn;
String shortResult, longResult;
public RecyclerViewHolder2(#NonNull View itemView, final OnItemClickListener listener2) {
super(itemView, listener2);
inputFahValueET = itemView.findViewById(R.id.input_fahrenheit_value_to_convert2);
convertResult = itemView.findViewById(R.id.output_result_ftk);
tempIconAndConvertBtn = itemView.findViewById(R.id.temp_icon_convert_btn2);
deleteCardBtn = itemView.findViewById(R.id.remove_card2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener2 != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener2.onItemClick(position);
}
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return position % 2 * 2;
}
public RecyclerItemAdapter(ArrayList<RecyclerItem> rList) {
recyclerItemList = rList;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fahrenheit_to_celsius_converter_layout, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v, (OnItemClickListener) recyclerItemListener);
return recyclerViewHolder;
case 2:
View v2 = LayoutInflater.from(parent.getContext()).inflate(R.layout.fahrenheit_to_kelvin_converter_layout, parent, false);
RecyclerViewHolder2 recyclerViewHolder2 = new RecyclerViewHolder2(v2, (OnItemClickListener) recyclerItemListener);
return recyclerViewHolder2;
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0: RecyclerViewHolder viewHolder = (RecyclerViewHolder) holder;
RecyclerItem currentItem = recyclerItemList.get(position);
final String[] result = new String[1];
viewHolder.tempIconAndConvertBtn.setOnClickListener(new View.OnClickListener() {...}
viewHolder.deleteCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeCard(viewHolder.getLayoutPosition());
}
});
break;
case 2: RecyclerViewHolder2 viewHolder2 = (RecyclerViewHolder2)holder;
RecyclerItem currentItem2 = recyclerItemList.get(position);
final String[] result2 = new String[1];
viewHolder2.tempIconAndConvertBtn.setOnClickListener(new View.OnClickListener() {...}
viewHolder2.deleteCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeCard(viewHolder2.getLayoutPosition());
}
});
break;
}
}
#Override
public int getItemCount() {
return recyclerItemList.size();
}
public void removeCard(int position) {
recyclerItemList.remove(position);
notifyItemRemoved(position);
}
}
public class RecyclerItem {
public RecyclerItem() {
}
}
I appreciate your help!
Full Adapter Class
public static class RecyclerItemAdapter extends RecyclerView.Adapter<RecyclerItemAdapter.RecyclerViewHolder> {
public ArrayList<RecyclerItem> recyclerItemList;
public AdapterView.OnItemClickListener recyclerItemListener;
public List<String> converterType;
public interface OnItemClickListener {
void onItemClick (int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
recyclerItemListener = (AdapterView.OnItemClickListener) listener;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
EditText inputFahValueET;
TextView convertResult;
ImageView tempIconAndConvertBtn;
ImageView deleteCardBtn;
String shortResult, longResult;
public RecyclerViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
inputFahValueET = itemView.findViewById(R.id.input_fahrenheit_value_to_convert);
convertResult = itemView.findViewById(R.id.output_result_ftc);
tempIconAndConvertBtn = itemView.findViewById(R.id.temp_icon_convert_btn);
deleteCardBtn = itemView.findViewById(R.id.remove_card);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public static class RecyclerViewHolder2 extends RecyclerViewHolder {
EditText inputFahValueET;
TextView convertResult;
ImageView tempIconAndConvertBtn;
ImageView deleteCardBtn;
String shortResult, longResult;
public RecyclerViewHolder2(#NonNull View itemView, final OnItemClickListener listener2) {
super(itemView, listener2);
inputFahValueET = itemView.findViewById(R.id.input_fahrenheit_value_to_convert2);
convertResult = itemView.findViewById(R.id.output_result_ftk);
tempIconAndConvertBtn = itemView.findViewById(R.id.temp_icon_convert_btn2);
deleteCardBtn = itemView.findViewById(R.id.remove_card2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener2 != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener2.onItemClick(position);
}
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return recyclerItemList.get(position).getType;
}
public RecyclerItemAdapter(ArrayList<RecyclerItem> rList) {
recyclerItemList = rList;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fahrenheit_to_celsius_converter_layout, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v, (OnItemClickListener) recyclerItemListener);
return recyclerViewHolder;
case 1:
View v2 = LayoutInflater.from(parent.getContext()).inflate(R.layout.fahrenheit_to_kelvin_converter_layout, parent, false);
RecyclerViewHolder2 recyclerViewHolder2 = new RecyclerViewHolder2(v2, (OnItemClickListener) recyclerItemListener);
return recyclerViewHolder2;
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0: RecyclerViewHolder viewHolder = (RecyclerViewHolder) holder;
RecyclerItem currentItem = recyclerItemList.get(position);
final String[] result = new String[1];
viewHolder.tempIconAndConvertBtn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View view) {
String getIputFahValue = viewHolder.inputFahValueET.getText().toString();
NumberFormat nf = new DecimalFormat("0.000");
if (!getIputFahValue.isEmpty()) {
double d = Double.parseDouble(getIputFahValue);
double dd = d - 32;
double ddd = dd * 5;
double dddd = ddd / 9;
result[0] = Double.toString(dddd);
viewHolder.convertResult.setText(nf.format(dddd) + "°C");
viewHolder.convertResult.setVisibility(View.VISIBLE);
viewHolder.shortResult = nf.format(dddd) + "°C";
viewHolder.longResult = getIputFahValue + "°F is " + nf.format(dddd) + "°C";
if (result[0].contains(".0")) {
result[0] = result[0].replace(".0", "");
viewHolder.convertResult.setText(result[0] + "°C");
viewHolder.convertResult.setVisibility(View.VISIBLE);
viewHolder.shortResult = result[0] + "°C";
viewHolder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
} else if (result[0].contains(".000")) {
result[0] = result[0].replace(".000", "");
viewHolder.convertResult.setText(result[0] + "°C");
viewHolder.convertResult.setVisibility(View.VISIBLE);
viewHolder.shortResult = result[0] + "°C";
viewHolder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
}
} else {
Toast.makeText(view.getContext(), "Fahrenheit Value Field Cannot Be Blank!", Toast.LENGTH_LONG).show();
}
}
});
viewHolder.convertResult.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder adb = new AlertDialog.Builder(view.getContext());
adb.setIcon(R.drawable.ic_baseline_file_copy_32);
adb.setTitle("Copy Result");
adb.setMessage("You can copy the result to your clipboard if you would like. Choose if you want the short or long result copied to your clipboard.\n\nExample of Short and Long Result:\nShort Result: 32°C\nLong Result: 0°F is 32°C");
adb.setPositiveButton("Short", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.shortResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNegativeButton("Long", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.longResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
adb.create();
adb.show();
return false;
}
});
viewHolder.deleteCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeCard(viewHolder.ge);
}
});
break;
case 2: RecyclerViewHolder2 viewHolder2 = (RecyclerViewHolder2)holder;
RecyclerItem currentItem2 = recyclerItemList.get(position);
final String[] result2 = new String[1];
viewHolder2.tempIconAndConvertBtn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View view) {
String getIputFahValue = viewHolder2.inputFahValueET.getText().toString();
NumberFormat nf = new DecimalFormat("0.000");
if (!getIputFahValue.isEmpty()) {
double d = Double.parseDouble(getIputFahValue);
double dd = d - 32;
double ddd = dd * 5;
double dddd = ddd / 9;
double ddddd = dddd + 273.15;
result2[0] = Double.toString(ddddd);
viewHolder2.convertResult.setText(nf.format(ddddd) + "°K");
viewHolder2.convertResult.setVisibility(View.VISIBLE);
viewHolder2.shortResult = nf.format(dddd) + "°K";
viewHolder2.longResult = getIputFahValue + "°F is " + nf.format(dddd) + "°K";
if (result2[0].contains(".0")) {
result2[0] = result2[0].replace(".0", "");
viewHolder2.convertResult.setText(result2[0] + "°K");
viewHolder2.convertResult.setVisibility(View.VISIBLE);
viewHolder2.shortResult = result2[0] + "°K";
viewHolder2.longResult = getIputFahValue + "°F is " + result2[0] + "°K";
} else if (result2[0].contains(".000")) {
result2[0] = result2[0].replace(".000", "");
viewHolder2.convertResult.setText(result2[0] + "°K");
viewHolder2.convertResult.setVisibility(View.VISIBLE);
viewHolder2.shortResult = result2[0] + "°K";
viewHolder2.longResult = getIputFahValue + "°F is " + result2[0] + "°K";
}
} else {
Toast.makeText(view.getContext(), "Fahrenheit Value Field Cannot Be Blank!", Toast.LENGTH_LONG).show();
}
}
});
viewHolder2.convertResult.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder adb = new AlertDialog.Builder(view.getContext());
adb.setIcon(R.drawable.ic_baseline_file_copy_32);
adb.setTitle("Copy Result");
adb.setMessage("You can copy the result to your clipboard if you would like. Choose if you want the short or long result copied to your clipboard.\n\nExample of Short and Long Result:\nShort Result: 283.15°K\nLong Result: 50°F is 283.15°K");
adb.setPositiveButton("Short", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.shortResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNegativeButton("Long", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.longResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
adb.create();
adb.show();
return false;
}
});
viewHolder2.deleteCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeCard(viewHolder2.getLayoutPosition());
}
});
break;
}
}
#Override
public int getItemCount() {
return recyclerItemList.size();
}
public void removeCard(int position) {
recyclerItemList.remove(position);
notifyItemRemoved(position);
}
}
public static class RecyclerItem {
public int getType;
int type;
public RecyclerItem(int mType) {
this.getType = mType;
}
public int getType() {
return type();
}
private int type() {
return type;
}
}
}
well there's some mistakes I suspect so I will try and suggest some things maybe it fixes your code behavior.
in removing the card, consider using holder.getAbsoluteAdapterPosition() instead of viewHolder.getLayoutPosition() or getAdapterPosition.
on adding any card, stop creating a new Adapter and LayoutManager over and over again, this components should be created once for any RecylcerView, just keep a reference to only the first old created adapter as a global variable, add the new card to the data ArrayList that the old adapter has reference to, use adapter.notifyDataSetChanged() on the old adapter reference that you're keeping as global variable.
I don't know how the viewType algorithm works, but if the options from add button decide which one you want, store an index to which card you want in the RecyclerItem object itself and in getItemViewType that you're overriding get the item at the required position and return its stored type rather than this strange position calculation (position%2*2).
by doing that make switch cases according to the integer values that you will be storing in ftoc/ftok/...etcConverterLabelBtn.setOnClickListener.
that would be a solution that it doesn't add or delete the right type of card in correspondence to your add/delete choices since your viewType algorithm will return value based on just the position not your choice.
anytime I used setHasFixedSize(true) it caused me trouble, so if you don't have a good reason to be using this, I suggest that you delete/comment its line of code completely
Update
your code should be looking like this :
Main Activity
public class MainActivity extends AppCompatActivity {
ArrayList<RecyclerItem> addConverterCard ;
private RecyclerView recyclerView;
private RecyclerItemAdapter recyclerItemAdapter;
private RecyclerView.LayoutManager layoutManager;
public TextView ftocConverterLabelBtn, ftokConverterLabelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_item_view);
ftocConverterLabelBtn = findViewById(R.id.add_f_to_c_converter_label_btn);
ftokConverterLabelBtn = findViewById(R.id.add_f_to_k_converter_label_btn);
addConverterCard = new ArrayList<>();
recyclerItemAdapter = new RecyclerItemAdapter(addConverterCard);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
addConverterCard.add(new RecyclerItem(0));
recyclerItemAdapter.notifyDataSetChanged();
closeActionButton();
}
}
});
ftokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
addConverterCard.add(new RecyclerItem(1));
recyclerItemAdapter.notifyDataSetChanged();
closeActionButton();
}
}
});
Adapter code
public static class RecyclerItemAdapter extends RecyclerView.Adapter<RecyclerItemAdapter.RecyclerViewHolder> {
public ArrayList<RecyclerItem> recyclerItemList;
public AdapterView.OnItemClickListener recyclerItemListener;
public List<String> converterType;
public interface OnItemClickListener {
void onItemClick (int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
recyclerItemListener = (AdapterView.OnItemClickListener) listener;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
EditText inputFahValueET;
TextView convertResult;
ImageView tempIconAndConvertBtn;
ImageView deleteCardBtn;
String shortResult, longResult;
public RecyclerViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
inputFahValueET = itemView.findViewById(R.id.input_fahrenheit_value_to_convert);
convertResult = itemView.findViewById(R.id.output_result_ftc);
tempIconAndConvertBtn = itemView.findViewById(R.id.temp_icon_convert_btn);
deleteCardBtn = itemView.findViewById(R.id.remove_card);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAbsoluteAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public static class RecyclerViewHolder2 extends RecyclerViewHolder {
EditText inputFahValueET;
TextView convertResult;
ImageView tempIconAndConvertBtn;
ImageView deleteCardBtn;
String shortResult, longResult;
public RecyclerViewHolder2(#NonNull View itemView, final OnItemClickListener listener2) {
super(itemView, listener2);
inputFahValueET = itemView.findViewById(R.id.input_fahrenheit_value_to_convert2);
convertResult = itemView.findViewById(R.id.output_result_ftk);
tempIconAndConvertBtn = itemView.findViewById(R.id.temp_icon_convert_btn2);
deleteCardBtn = itemView.findViewById(R.id.remove_card2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener2 != null) {
int position = getAbsoluteAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener2.onItemClick(position);
}
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return recyclerItemList.get(position).getType();
}
public RecyclerItemAdapter(ArrayList<RecyclerItem> rList) {
recyclerItemList = rList;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fahrenheit_to_celsius_converter_layout, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v, (OnItemClickListener) recyclerItemListener);
return recyclerViewHolder;
case 1:
View v2 = LayoutInflater.from(parent.getContext()).inflate(R.layout.fahrenheit_to_kelvin_converter_layout, parent, false);
RecyclerViewHolder2 recyclerViewHolder2 = new RecyclerViewHolder2(v2, (OnItemClickListener) recyclerItemListener);
return recyclerViewHolder2;
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0: RecyclerViewHolder viewHolder = (RecyclerViewHolder) holder;
RecyclerItem currentItem = recyclerItemList.get(position);
final String[] result = new String[1];
viewHolder.tempIconAndConvertBtn.setOnClickListener(new View.OnClickListener() {...});
viewHolder.deleteCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeCard(holder.getAbsoluteAdapterPosition());
}
});
break;
case 1: RecyclerViewHolder2 viewHolder2 = (RecyclerViewHolder2)holder;
RecyclerItem currentItem2 = recyclerItemList.get(position);
final String[] result2 = new String[1];
viewHolder2.tempIconAndConvertBtn.setOnClickListener(new View.OnClickListener() {...});
viewHolder2.deleteCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeCard(holder.getAbsoluteAdapterPosition());
}
});
break;
}
}
#Override
public int getItemCount() {
return recyclerItemList.size();
}
public void removeCard(int position) {
recyclerItemList.remove(position);
notifyItemRemoved(position);
}
public class RecyclerItem {
int type ;
public RecyclerItem(int m_type) {
this.type = m_type ;
}
public int getType(){
return type;
}
}
}
I have created a Nested recycle rview with parent and child both dynamic.Addition to both Parent and Child is working fine.Deletion from child is working fine.I want to remove parent view when all the child views for the same is removed.Confused about how could i implement the same.
Here is the child Adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ToDoModel> values;
private Context context;
//private OnEditListener onEditListener;
AlertDialog alertDialog;
/*public MyAdapter(List<ToDoModel> context) {
this.values = context;
this.onEditListener = onEditListener;
}*/
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtHeader;
public TextView txtFooter;
public ImageView mIcon;
public View layout;
public ImageView deleteItem;
public CheckBox doneButton;
public ImageView editItem;
public ViewHolder(View v) {
super(v);
layout = v;
txtHeader = (TextView) v.findViewById(R.id.firstLine);
txtFooter = (TextView) v.findViewById(R.id.secondLine);
mIcon = (ImageView) v.findViewById(R.id.icon);
deleteItem = (ImageView) v.findViewById(R.id.deleteButton);
doneButton = (CheckBox) v.findViewById(R.id.checkBox);
editItem = (ImageView) v.findViewById(R.id.editButton);
}
}
public void add(int position, ToDoModel item) {
values.add(position, item);
sort();
notifyDataSetChanged();
//notifyItemInserted(position);
}
public void replace(ToDoModel item)
{
int editPos;
editPos = values.indexOf(item);
values.set(editPos,item);
sort();
notifyDataSetChanged();
}
public void sort() {
if ((int) values.size() > 1) {
Collections.sort(values);
}
}
public void remove(int position) {
values.remove(position);
notifyDataSetChanged();
}
public MyAdapter(List<ToDoModel> myDataset) {
values = myDataset;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.todo_row_view, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final ToDoModel toDoModel = values.get(position);
switch ((String) toDoModel.task) {
case "To Go":
holder.mIcon.setImageResource(R.drawable.ic_explore24px);
break;
case "To Get":
holder.mIcon.setImageResource(R.drawable.ic_shoppingbag24px);
break;
case "To Do":
holder.mIcon.setImageResource(R.drawable.ic_todo);
break;
default:
break;
}
holder.txtHeader.setText(toDoModel.header);
holder.txtFooter.setText(toDoModel.task + " | " + toDoModel.tod + " | " + toDoModel.footer);
holder.doneButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isChecked()) {
//holder.mIcon.setImageResource(R.drawable.ic_check_circle24px);
Toast.makeText(buttonView.getContext(), "Marked As Done", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(buttonView.getContext(), "Marked As UnDone", Toast.LENGTH_SHORT).show();
}
}
});
holder.deleteItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
View view = LayoutInflater.from(v.getContext()).inflate(R.layout.delete_promptdialog,null);
Button YesButton = (Button) view.findViewById(R.id.buttonYes);
Button NoButton = (Button) view.findViewById(R.id.buttonNo);
YesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
remove(position);
Toast.makeText(v.getContext(), "List Item Removed", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
NoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Delete Canceled", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
builder.setView(view);
alertDialog=builder.create();
alertDialog.show();
/*remove(position);
Toast.makeText(v.getContext(), "List Item Removed", Toast.LENGTH_SHORT).show();*/
}
});
/* holder.editItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onEditListener.onEditClick(values.get(position));
//Toast.makeText(v.getContext(), "List Edit", Toast.LENGTH_SHORT).show();
}
});*/
}
/*public interface OnEditListener {
void onEditClick(ToDoModel currentData);
}*/
#Override
public int getItemCount() {
return values.size();
}
}
Here is the Parent Adapter
public class ParentAdapter extends RecyclerView.Adapter<ParentAdapter.ParentViewHolder> {
private RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
public List<TodoParent> parentList;
public TodoParent todayList;
public static long todayEpochDate;
public ParentAdapter(List<TodoParent> parentList, MainFragment mainFragment) {
this.parentList = parentList;
}
public void add(int position, TodoParent item) {
parentList.add(position, item);
sort();
notifyDataSetChanged();
//notifyItemInserted(position);
}
public void sort() {
if ((int) parentList.size() > 1) {
Collections.sort(parentList);
//if(!(todayList.ParentTitle.isEmpty())) Collections.swap(parentList, parentList.indexOf(todayList), 0);
}
/* if ( todayList )
{
System.out.println("Entering Swap");
setToday(todayList);
}*/
}
public void setToday(TodoParent item) {
int todayPos;
todayPos = parentList.indexOf(item);
parentList.remove(todayPos);
notifyDataSetChanged();
parentList.add(0,item);
notifyDataSetChanged();
}
#NonNull
#Override
public ParentAdapter.ParentViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.todo_parent_view,parent,false);
ParentViewHolder vh = new ParentViewHolder(view);
return vh;
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull ParentViewHolder holder, int position) {
TodoParent todoParent = parentList.get(position);
todoParent.ParentId = position;
Calendar mCal;
mCal = Calendar.getInstance();
int mDay = mCal.get(Calendar.DAY_OF_MONTH);
int mMonth = mCal.get(Calendar.MONTH);
int mYear = mCal.get(Calendar.YEAR);
String dateString = mDay +"/"+ (mMonth+1) +"/" + mYear;
try {
todayEpochDate = new SimpleDateFormat("dd/MM/yyyy").parse(dateString).getTime()/1000;
} catch (ParseException e) {
e.printStackTrace();
}
if((long)todayEpochDate == (long)todoParent.EpochTime)
{
holder.mTitle.setText("Today");
todayList = todoParent;
System.out.println("todayE:"+todayEpochDate);
System.out.println("SelectedE:"+todoParent.EpochTime);
}
else
{
holder.mTitle.setText(todoParent.ParentTitle);
System.out.println("today:"+todayEpochDate);
System.out.println("Selected:"+todoParent.EpochTime);
}
LinearLayoutManager layoutManager = new LinearLayoutManager(holder.childView.getContext(),
LinearLayoutManager.VERTICAL,false);
layoutManager.setInitialPrefetchItemCount(todoParent.mChildList.size());
holder.childView.setLayoutManager(layoutManager);
MyAdapter myAdapter = new MyAdapter(todoParent.mChildList);
holder.childView.setAdapter(myAdapter);
holder.childView.setRecycledViewPool(viewPool);
}
#Override
public int getItemCount() {
return parentList.size();
}
public class ParentViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public RecyclerView childView;
public ParentViewHolder(#NonNull View itemView) {
super(itemView);
mTitle = itemView.findViewById(R.id.mParentTitle);
childView = itemView.findViewById(R.id.mChildView);
}
}
}
remove for child is working fine. How to remove Parent here when there are no more child views?
//I have recycler view as follows
private void prepareGridRecycleView() {
gridRecyclerView.setHasFixedSize(true);
SpaceItemGridDecoration itemDecoration = new SpaceItemGridDecoration(10);
gridRecyclerView.setClipToPadding(false);
gridRecyclerView.addItemDecoration(itemDecoration);
adapter = new ShopPageGridViewAdapter(ShopPageContent.this, new ShopPageHeaderGridInterface() {
#Override
public void onClick(boolean isClicked) {
gridRecyclerView.setVisibility(View.INVISIBLE);
listRecycleView.setVisibility(View.VISIBLE);
}
}, new ShopPageHeaderListInterface() {
#Override
public void onClick(boolean isClicked) {
}
}, new CartCoordivateInfoHolder() {
#Override
public void setViewCoordinate(ImageView view, int x, int y) {
view.setVisibility(View.VISIBLE);
int pos[] = new int[2];
cart.getLocationOnScreen(pos);
Log.e("x", String.valueOf(pos[0]));
Log.e("y", String.valueOf(pos[1]));
view.bringToFront();
Animations anim = new Animations();
Animation a = anim.fromAtoB(20, 30, 6000,6000,null,850);
a.setFillAfter(true);
view.setAnimation(a);
a.startNow();
}
}, new ShopPageHeaderHelpInterface() {
#Override
public void onClick(boolean isClicked) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShopPageContent.this);
View view = getLayoutInflater().inflate(R.layout.help_dialog, null);
builder.setView(view);
AlertDialog alertDialog = builder.create();
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(true);
}
}, new ShopPageHeaderFilterInterface() {
#Override
public void onClick(boolean isClick) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShopPageContent.this);
View view = getLayoutInflater().inflate(R.layout.filter_dialog, null);
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.circle_view_child);
RangeSeekbar seekBar = (RangeSeekbar) view.findViewById(R.id.seekbar);
seekBar.setTextMarkSize(0);
prepareCircleImage(linearLayout);
final TextView s = (TextView) view.findViewById(R.id.s);
final TextView m = (TextView) view.findViewById(R.id.m);
final TextView l = (TextView) view.findViewById(R.id.l);
final TextView xl = (TextView) view.findViewById(R.id.xl);
final TextView xxl = (TextView) view.findViewById(R.id.xxl);
final TextView xxxl = (TextView) view.findViewById(R.id.xxxl);
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBackground(s);
}
});
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBackground(l);
}
});
m.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBackground(m);
}
});
xl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBackground(xl);
}
});
xxl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBackground(xxl);
}
});
xxxl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBackground(xxxl);
}
});
builder.setView(view);
AlertDialog alertDialog = builder.create();
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(true);
}
});
final GridLayoutManager manager = new GridLayoutManager(this, 2);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return adapter.isPositionHeader(position) ? manager.getSpanCount() : 1;
}
});
gridRecyclerView.setAdapter(adapter);
gridRecyclerView.setLayoutManager(manager);
}
//the recycler view adapter seems as follows
public class ShopPageGridViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private List<String> list = new ArrayList<>();
private Context context;
private ShopPageHeaderGridInterface shopPageHeaderGridInterface;
private ShopPageHeaderListInterface shopPageHeaderListInterface;
private ShopPageHeaderFilterInterface shopPageHeaderFilterInterface;
private CartCoordivateInfoHolder cartCoordivateInfoHolder;
private ShopPageHeaderHelpInterface shopPageHeaderHelpInterface;
public ShopPageGridViewAdapter(Context context, ShopPageHeaderGridInterface shopPageHeaderGridInterface, ShopPageHeaderListInterface shopPageHeaderListInterface, CartCoordivateInfoHolder cartCoordivateInfoHolder, ShopPageHeaderHelpInterface shopPageHeaderHelpInterface, ShopPageHeaderFilterInterface shopPageHeaderFilterInterface) {
this.context = context;
this.shopPageHeaderGridInterface = shopPageHeaderGridInterface;
this.shopPageHeaderListInterface = shopPageHeaderListInterface;
this.cartCoordivateInfoHolder = cartCoordivateInfoHolder;
this.shopPageHeaderHelpInterface = shopPageHeaderHelpInterface;
this.shopPageHeaderFilterInterface = shopPageHeaderFilterInterface;
for (int i = 0; i <= 10; i++) {
list.add("hello");
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HEADER) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.shop_page_grid_layout_header, parent, false);
final ImageView heroImageView = (ImageView) v.findViewById(R.id.heroImageView);
heroImageView.post(new Runnable() {
#Override
public void run() {
heroImageView.getLayoutParams().height = (int) (heroImageView.getWidth() * 0.63);
}
});
final ImageView stackImage = (ImageView) v.findViewById(R.id.stack_image);
ImageView helpImage = (ImageView) v.findViewById(R.id.help);
final ImageView filterImage = (ImageView) v.findViewById(R.id.filter_image);
stackImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shopPageHeaderGridInterface.onClick(true);
}
});
final ImageView gridImage = (ImageView) v.findViewById(R.id.grid_image);
gridImage.post(new Runnable() {
#Override
public void run() {
gridImage.getLayoutParams().height = (int) (gridImage.getHeight() * 0.80);
gridImage.getLayoutParams().width = (int) (gridImage.getWidth() * 0.80);
stackImage.getLayoutParams().height = (int) (stackImage.getHeight() * 0.80);
stackImage.getLayoutParams().width = (int) (stackImage.getWidth() * 0.80);
filterImage.getLayoutParams().height = (int) (filterImage.getHeight() * 0.80);
filterImage.getLayoutParams().width = (int) (filterImage.getWidth() * 0.80);
}
});
gridImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shopPageHeaderListInterface.onClick(true);
}
});
helpImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shopPageHeaderHelpInterface.onClick(true);
}
});
filterImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shopPageHeaderFilterInterface.onClick(true);
}
});
return new VHHeader(v);
} else if (viewType == TYPE_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.shop_page_grid_layout, parent, false);
final RelativeLayout relativeLayout = (RelativeLayout) v.findViewById(R.id.grid_parent);
final ImageView gridItemImage=(ImageView)v.findViewById(R.id.grid_item_image);
new Handler().post(new Runnable() {
#Override
public void run() {
relativeLayout.getLayoutParams().height = (int) (relativeLayout.getWidth() * 1.2);
relativeLayout.requestLayout();
gridItemImage.setImageResource(R.drawable.winter_sale);
}
});
final ImageView cart = (ImageView) v.findViewById(R.id.cart);
final ImageView cartNumber = (ImageView) v.findViewById(R.id.cart_number);
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos[] = new int[2];
cartNumber.getLocationOnScreen(pos);
Log.e("x", String.valueOf(pos[0]));
Log.e("y", String.valueOf(pos[1]));
cartCoordivateInfoHolder.setViewCoordinate(cartNumber, pos[0], pos[1]);
}
});
return new VHItem(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof VHHeader) {
VHHeader VHheader = (VHHeader) holder;
} else if (holder instanceof VHItem) {
VHItem VHitem = (VHItem) holder;
}
}
// need to override this method
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
public boolean isPositionHeader(int position) {
return position == 0;
}
//increasing getItemcount to 1. This will be the row of header.
#Override
public int getItemCount() {
return list.size() + 1;
}
class VHHeader extends RecyclerView.ViewHolder {
public VHHeader(View itemView) {
super(itemView);
}
}
class VHItem extends RecyclerView.ViewHolder {
public VHItem(View itemView) {
super(itemView);
}
}
}
//So the problem I am facing is I have cart image in recycler view item and when clicked the cart image should translate to the cart icon at toolbar.But when clicked in recycler view ,item at the cart moves around in item and not comes outside of recycler view..
Well you can achieve this in many ways but i think sharedElementTransition will just do the thing for you
Use SharedElementTransition which make it easier as all the thing will be done by the android system itself you can reffer SharedElementTransition
Hope it Helped :)