I'm having this issue where the old viewHolder of a position in the recyclerview isn't deleted or reset before recycling it. In my case this means that if I scroll and go back to the former position it now has two views stacked on top of each other. I tried solving this by setting the visiblity of the view to be inflated to gone but this is a solution for the short run and I want to understand how to really solve this. I also tried to setRecycble(false) but then my views take longer to inflate and recycling the views also makes more sense My Adapter code is below:
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.chatr.app.android.Interfaces.MessageListParent;
import com.chatr.app.android.Models.ChatrInvitePending;
import com.chatr.app.android.Models.ChatrMessagingInfo;
import com.chatr.app.android.R;
import com.chatr.app.android.Repositories.MessageRepository;
import com.chatr.app.android.RoomDB.ChatDatabase.ChatEntity;
import com.chatr.app.android.RoomDB.MessagesDatabase.MessageEntity;
import com.chatr.app.android.Tools.ChatrApplication;
import com.chatr.app.android.Tools.ChatrErrorHandler;
import com.chatr.app.android.Views.MessageItemView;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.chatr.app.android.Manager.MessageManager.CONSTANT_OTHER_TYPE;
import static com.chatr.app.android.Manager.MessageManager.CONSTANT_SELF_TYPE;
public class MessageListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//Constants
private static final String TAG = "MessageListAdapter";
private static final int CONSTANT_MESSAGE_TYPE = 0;
private static final int CONSTANT_INFORMATION_TYPE = 1;
//Data list
private final ArrayList<MessageEntity> messageEntityList = new ArrayList<>();
private final ArrayList<Object> additionalInformationList = new ArrayList<>();
//Callback
private final MessageListParent parentCallback;
public MessageListAdapter(MessageListParent parent) {
this.parentCallback = parent;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
if (viewType == CONSTANT_MESSAGE_TYPE) {
MessageItemView messageItemView = new MessageItemView(parent.getContext());
messageItemView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
viewHolder = new MessageViewHolder(messageItemView);
}
else if(viewType == CONSTANT_INFORMATION_TYPE){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_chat_view_information_text,parent);
//v.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
viewHolder = new InformationTextViewHolder(v);
}
return viewHolder;
}
#Override
public int getItemViewType(int position) {
Object v = null;
for(Object obj : additionalInformationList){
if (additionalInformationList.get(position) instanceof ChatrInvitePending){
if (((ChatrInvitePending)
additionalInformationList.get(position)).getRecyclerViewPosition() == position){
v = obj;
break;
}
}
else if (additionalInformationList.get(position) instanceof ChatrMessagingInfo){
if (((ChatrMessagingInfo)
additionalInformationList.get(position)).getRecyclerViewPosition() == position){
v = obj;
break;
}
}
}
if (v == null){
return CONSTANT_MESSAGE_TYPE;
}
else{
return CONSTANT_INFORMATION_TYPE;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()){
case CONSTANT_MESSAGE_TYPE:
generateMessageTypeView((MessageViewHolder) holder, position);
case CONSTANT_INFORMATION_TYPE:
//generateInformationTypeView((InformationTextViewHolder) holder, position);
}
}
public void generateMessageTypeView(MessageViewHolder holder, int position) {
try{
holder.messageItemView.setFormerEntity(messageEntityList.get(position-1));
}catch (Exception e){
ChatrErrorHandler.handleException(e);
}
holder.messageItemView.setEntity(messageEntityList.get(position));
if(!messageEntityList.get(position).isRead()) {
parentCallback.viewIsRead(messageEntityList.get(position));
}
}
#Override
public int getItemCount() {
return messageEntityList.size();
}
public void updateMessageList(List<MessageEntity> messageEntitiesList) {
this.messageEntityList.clear();
this.messageEntityList.addAll(new ArrayList<>(messageEntitiesList));
notifyItemInserted(messageEntitiesList.size());
}
public void updateAdditionalInfoList(List<Object> additionalList) {
this.additionalInformationList.clear();
this.additionalInformationList.addAll(new ArrayList<>(additionalList));
notifyItemInserted(additionalList.size());
}
#Override
public void onViewRecycled(#NonNull #NotNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
MessageViewHolder messageViewHolder = (MessageViewHolder) holder;
messageViewHolder.messageItemView.clear();
}
public static class MessageViewHolder extends RecyclerView.ViewHolder{
private final MessageItemView messageItemView;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
messageItemView = (MessageItemView) itemView;
}
}
public static class InformationTextViewHolder extends RecyclerView.ViewHolder{
private final TextView textView;
public InformationTextViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.title_information_text_chat);
}
}
}
Here you can see the issue I have:
Here is my view that I inflate:
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.chatr.app.android.Manager.MediaManager;
import com.chatr.app.android.Manager.MessageManager;
import com.chatr.app.android.R;
import com.chatr.app.android.Repositories.ChatRepository;
import com.chatr.app.android.Repositories.MessageRepository;
import com.chatr.app.android.RoomDB.ChatDatabase.ChatEntity;
import com.chatr.app.android.RoomDB.MediaDatabase.MediaEntity;
import com.chatr.app.android.RoomDB.MessagesDatabase.MessageEntity;
import org.jetbrains.annotations.NotNull;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MessageItemView extends FrameLayout {
private static final long CONSTANT_TIME_5_MIN = 300000;
private int viewType = 1;
private MessageEntity messageEntity;
private TextView txtContent;
private TextView txtTime;
private ImageView imageView;
private AudioMessageView audioMessageView;
private ChatrGradientView chatrGradientView;
private final String regexEmoji = "([\\u20a0-\\u32ff\\ud83c\\udc00-\\ud83d\\udeff\\udbb9\\udce5-\\udbb9\\udcee])";
private static final String TAG = "MessageItemView";
private MessageEntity formerMessageEntity;
public MessageItemView(#NonNull Context context) {
super(context);
}
public MessageItemView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public MessageItemView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MessageItemView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
private void init() {
Log.d(TAG, "init: " + viewType);
if (viewType == MessageManager.CONSTANT_OTHER_TYPE) {
Log.d(TAG, "init:3 ");
LayoutInflater.from(getContext()).inflate(R.layout.layout_chat_other_message_view_item, this);
}
if (viewType == MessageManager.CONSTANT_SELF_TYPE) {
Log.d(TAG, "ini2t: " + viewType);
LayoutInflater.from(getContext()).inflate(R.layout.layout_chat_self_message_view_item, this);
}
initViews();
}
#NotNull
public String convertMillisToTime(long millis) {
Log.d(TAG, "convertMillisToTime: " + millis);
DateFormat formatter = new SimpleDateFormat("HH:mm", Locale.GERMANY);
formatter.setTimeZone(TimeZone.getTimeZone("GMT+2" +
""));
return formatter.format(new Date(millis*1000));
}
private void initViews() {
Log.d(TAG, "initViews: ");
imageView = findViewById(R.id.img_content_message_item);
txtContent = findViewById(R.id.txt_content_message_item);
txtTime = findViewById(R.id.message_date_indicator_txt);
chatrGradientView = findViewById(R.id.img_message_item_profile_pic);
audioMessageView = findViewById(R.id.audio_message_view_in_message);
ChatRepository.get(getContext())
.getStartGradientChatEntity(messageEntity.getChatId(), new ChatRepository.GetGradient() {
#Override
public void getGradient(int color) {
chatrGradientView.setGradientStartColor(color);
}
});
ChatRepository.get(getContext())
.getEndGradientChatEntity(messageEntity.getChatId(), new ChatRepository.GetGradient() {
#Override
public void getGradient(int color) {
chatrGradientView.setGradientEndColor(color);
}
});
imageView.setVisibility(GONE);
txtContent.setVisibility(VISIBLE);
if (formerMessageEntity == null || formerMessageEntity.getDateSent() > CONSTANT_TIME_5_MIN ){
txtTime.setVisibility(VISIBLE);
txtTime.setText(convertMillisToTime(messageEntity.getDateSent()));
}
if (messageEntity != null) {
imageView.setVisibility(GONE);
txtContent.setVisibility(VISIBLE);
txtContent.setText(messageEntity.getContentText());
}
Log.d(TAG, "run-3: ");
if (messageEntity.getMediaId()!= -1){
txtContent.setVisibility(GONE);
Log.d(TAG, "run-2: " + messageEntity.getMediaId());
MessageRepository.get(getContext()).getMediaWithId(messageEntity.getMediaId(),
new MessageRepository.getMediaEntity() {
#Override
public void getMedia(MediaEntity mediaEntity) {
Log.d(TAG, "run-1: " + mediaEntity);
mediaAvailabilityWork(mediaEntity);
}
});
}
else{
Glide.with(MessageItemView.this).clear(imageView);
imageView.setImageDrawable(null);
imageView.setVisibility(GONE);
}
Matcher matchEmo = Pattern.compile(regexEmoji).matcher(txtContent.getText());
while(matchEmo.find()){
Log.d(TAG, "initViews: ");
Spannable spannable = new SpannableString(txtContent.getText());
spannable.setSpan(new ForegroundColorSpan(Color.WHITE), matchEmo.start(),
matchEmo.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
txtContent.setText(spannable, TextView.BufferType.SPANNABLE);
}
}
public void mediaAvailabilityWork(MediaEntity mediaEntity) {
Log.d(TAG, "run0: ");
if (mediaEntity != null) {
Log.d(TAG, "run1: " +mediaEntity.getTypeMedia());
if (mediaEntity.getTypeMedia().equals(MediaManager.CONSTANT_MEDIA_TYPE_AUDIO)){
audioMessageView.post(new Runnable(){
#Override
public void run() {
Log.d(TAG, "run2: ");
audioMessageView.setVisibility(VISIBLE);
imageView.setVisibility(GONE);
audioMessageView.setMediaEntity(mediaEntity);
}
});
}
else if (mediaEntity.getTypeMedia().equals(MediaManager.CONSTANT_MEDIA_TYPE_IMG)){
imageView.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "run3123123: ");
imageView.setVisibility(VISIBLE);
audioMessageView.setVisibility(GONE);
Glide.with(MessageItemView.this).
load(mediaEntity.getFileUrl()).centerCrop().into(imageView);
}
});
}
}
}
public void setEntity(MessageEntity messageEntity) {
this.viewType = messageEntity.getChatType();
this.messageEntity = messageEntity;
Log.d(TAG, "setEntity: " + messageEntity.getMediaId());
init();
}
public void setFormerEntity(MessageEntity formerMessageEntity) {
this.formerMessageEntity = formerMessageEntity;
}
public void clear() {
viewType = 1;
txtTime.setText("");
txtContent.setText("");
audioMessageView.setVisibility(GONE);
txtContent.setVisibility(GONE);
this.postInvalidate();
}
}
Related
I am creating a document arrangement activity with RecyclerView. I want to arrange the document with drag and drop. It was done by using ItemTouchHelper.Callbackbut after that I can't set the page number after the OnItemMove callback. what should I do?
EDIT: added code snippet
package adapters;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.pdf.PdfRenderer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.mobilix.docscanner.R;
import java.util.ArrayList;
import java.util.Collections;
import helper.ItemTouchHelperAdapter;
import helper.ItemTouchHelperViewHolder;
import helper.OnStartDragListener;
import helper.SimpleItemTouchHelperCallback;
public class PageAjdustAdapter extends RecyclerView.Adapter<PageAjdustAdapter.PageAdjustHolder> implements ItemTouchHelperAdapter, OnStartDragListener {
private final String TAG = getClass().getName();
Context mContext;
ArrayList<PdfPage> pdfPages = new ArrayList<>();
private ItemTouchHelper itemTouchHelper;
public PageAjdustAdapter(Context context, ArrayList<PdfPage> pages) {
this.mContext = context;
pdfPages = pages;
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(this);
itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(((Activity) context).findViewById(R.id.rcvPageArrange));
}
#NonNull
#Override
public PageAdjustHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_page_adajustment, parent, false);
return new PageAdjustHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PageAdjustHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: ");
holder.ivPage.setImageBitmap(pdfPages.get(position).bitmap);
holder.cbPage.setChecked(pdfPages.get(position).isSelected);
holder.tvPageNo.setText(String.valueOf(position + 1));
holder.cbPage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
pdfPages.get(holder.getAdapterPosition()).isSelected = isChecked;
}
});
holder.ivRotate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getAdapterPosition();
pdfPages.get(pos).bitmap = Bitmap.createBitmap(//
pdfPages.get(pos).bitmap, 0, 0, pdfPages.get(pos).bitmap.getWidth(),//
pdfPages.get(pos).bitmap.getHeight(), pdfPages.get(pos).matrix, true);//
notifyItemChanged(pos);
}
});
}
#Override
public int getItemCount() {
return pdfPages.size();
}
#Override
public boolean onItemMove(int fromPosition, int toPosition) {
Log.d(TAG, "onItemMove: ->fp " + (fromPosition + 1) + " tp-> " + (toPosition + 1));
Collections.swap(pdfPages, fromPosition, toPosition);
notifyItemMoved(fromPosition, toPosition);
return false;
}
#Override
public void onItemDismiss(int position) {
pdfPages.remove(position);
notifyItemRemoved(position);
}
#Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
itemTouchHelper.startDrag(viewHolder);
}
public static class PageAdjustHolder extends RecyclerView.ViewHolder implements
ItemTouchHelperViewHolder {
ImageView ivPage, ivRotate;
CheckBox cbPage;
TextView tvPageNo;
public PageAdjustHolder(#NonNull View itemView) {
super(itemView);
ivPage = itemView.findViewById(R.id.ivPage);
ivRotate = itemView.findViewById(R.id.ivRotate);
cbPage = itemView.findViewById(R.id.cbPage);
tvPageNo = itemView.findViewById(R.id.tvPageNo);
}
#Override
public void onItemSelected() {
}
#Override
public void onItemClear() {
}
}
public static class PdfPage {
PdfRenderer.Page page;
Bitmap bitmap;
boolean isSelected;
Matrix matrix;
int rotate = 0;
public PdfPage(PdfRenderer.Page page, Bitmap bitmap) {
this.page = page;
this.bitmap = bitmap;
matrix = new Matrix();
rotate += 90;
matrix.postRotate(90);//martix work on +=90
}
}
}
You have to call notifyDataSetChanged() when an item position is changed. The easiest way it to used onItemClear(), it will be called when an item is de-selected. Add it like following.
#Override
public void onItemClear() {
notifyDataSetChanged();
}
One thing you have to add is check weather the position is actually changed after the drag operation or not other wise it will always update the whole dataset whenever an item is selected and than de-selected.
Edit
Create a local variable in view-holder class. Than you just have to set it in onItemSelected() and check it in onItemClear();
#Override
public void onItemSelected() {
lastpos = getAdapterPosition();
}
#Override
public void onItemClear() {
if(lastpos != getAdapterPosition())
notifyDataSetChanged();
}
I have implemented a expandable nested RecyclerView . Now I want to display an AlertDialog when an item of RecyclerView is clicked. I tried many ways and none of them worked. Here is my adapter class,
**Parent Adopter class code**'
$ package com.pscripto.mxmoviehub;
import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList; import java.util.List;
public class ParentAdopter extends RecyclerView.Adapter<ParentAdopter.ParentAdopterViewHolder> { private List<Movie_Model> movieModelList; private List<Child_Model> child_modelList; private ChildAdopter childAdopter; private Context context;
public ParentAdopter(#NonNull List<Movie_Model> movieModelList) {
this.movieModelList = movieModelList;
}
#NonNull
#Override
public ParentAdopterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View rootview = LayoutInflater.from(parent.getContext()).inflate(R.layout.vertical_rv,parent,false);
return new ParentAdopterViewHolder(rootview);
}
#SuppressLint("WrongConstant")
#Override
public void onBindViewHolder(#NonNull ParentAdopterViewHolder holder, int position) { Movie_Model movie_model = movieModelList.get(position); holder.tvSection.setText(movie_model.getHeaderTitle()); if (movie_model.getHeaderTitle().contains("Latest Movies")){ childAdopter= new ChildAdopter(getLatestMovie(),context);
} else if (movie_model.getHeaderTitle().contains("Action Movies")){
childAdopter= new ChildAdopter(getActionMovies(),context);
} else if (movie_model.getHeaderTitle().contains("Romantic Movies")){
childAdopter = new ChildAdopter(getRomanticMovies(),context); } holder.childRecyclerview.setHasFixedSize(true); holder.childRecyclerview.setLayoutManager(new LinearLayoutManager(context, LinearLayout.HORIZONTAL,false)); holder.childRecyclerview.setAdapter(childAdopter); //customClicl();
} private void customClicl(){
childAdopter.setCustomClickListener(new ChildAdopter.CustomClickListener() {
#Override
public void onItemClick(int position) {
Toast.makeText(context, "hi", Toast.LENGTH_SHORT).show();
}
}); }
private List<Child_Model> getLatestMovie(){ child_modelList = new ArrayList<>(); child_modelList.add(new Child_Model(R.drawable.salmankhanmovieone,"Bajrangi Bhaijaan"));
child_modelList.add(new Child_Model(R.drawable.pati,"Pati Patni Aur Woh"));
child_modelList.add(new Child_Model(R.drawable.blackmail,"Blackmail 2019"));
child_modelList.add(new Child_Model(R.drawable.bharat,"Bharat 2019"));
child_modelList.add(new Child_Model(R.drawable.gang,"Gangster 3"));
return child_modelList;
}
private List<Child_Model> getActionMovies(){
child_modelList = new ArrayList<>();
child_modelList.add(new Child_Model(R.drawable.salmankhanmovieone,"Bajrangi Bhaijaan"));
child_modelList.add(new Child_Model(R.drawable.blackmail,"Blackmail 2019"));
child_modelList.add(new Child_Model(R.drawable.bharat,"Bharat 2019"));
child_modelList.add(new Child_Model(R.drawable.gang,"Gangster 3"));
return child_modelList;
}
private List<Child_Model> getRomanticMovies(){
child_modelList = new ArrayList<>();
child_modelList.add(new Child_Model(R.drawable.star,"Love Star"));
child_modelList.add(new Child_Model(R.drawable.bestofme,"The Best Of Me"));
child_modelList.add(new Child_Model(R.drawable.trailer,"After Trailer"));
child_modelList.add(new Child_Model(R.drawable.buylove,"Cant Buy Love"));
return child_modelList;
}
#Override
public int getItemCount() {
return movieModelList.size();
}
class ParentAdopterViewHolder extends RecyclerView.ViewHolder { TextView tvSection; RecyclerView childRecyclerview;
public ParentAdopterViewHolder(#NonNull View itemView) {
super(itemView);
tvSection = itemView.findViewById(R.id.tvsection);
childRecyclerview = itemView.findViewById(R.id.child_rv);
}
}
}'$'
**Child adopter class**
package com.pscripto.mxmoviehub;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class ChildAdopter extends RecyclerView.Adapter<ChildAdopter.ChildAdopterViewHolder> {
private List<Child_Model> child_modelList;
private ChildAdopter childAdopter ;
private Context context;
private CustomClickListener customClickListener;
public void setCustomClickListener(CustomClickListener customClickListener) {
this.customClickListener = customClickListener;
}
interface CustomClickListener{
void onItemClick (int position);
}
public ChildAdopter(List<Child_Model> child_modelList, Context context) {
this.child_modelList = child_modelList;
this.context = context;
}
#NonNull
#Override
public ChildAdopterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View rootview = LayoutInflater.from(parent.getContext()).inflate(R.layout.horizental_layout, parent, false);
return new ChildAdopterViewHolder(rootview);
}
#Override
public void onBindViewHolder(#NonNull ChildAdopterViewHolder holder, int position) {
Child_Model child_model = child_modelList.get(position);
holder.movieImg.setImageResource(child_model.getImgResId());
holder.movieTitle.setText(child_model.getTitle());
Boolean isExpanded = child_modelList.get(position).getExpanded();
holder.expandidLayout.setVisibility(isExpanded ? View.VISIBLE : View.INVISIBLE);
}
#Override
public int getItemCount() {
return child_modelList.size();
}
class ChildAdopterViewHolder extends RecyclerView.ViewHolder {
private ImageView movieImg ,ivEdit,ivDel;
private TextView movieTitle;
LinearLayout expandidLayout;
public ChildAdopterViewHolder(#NonNull View itemView) {
super(itemView);
movieImg = itemView.findViewById(R.id.movie_img);
movieTitle = itemView.findViewById(R.id.movie_name);
expandidLayout = itemView.findViewById(R.id.expandable_layout);
ivEdit = itemView.findViewById(R.id.iv_Edit);
ivDel = itemView.findViewById(R.id.del_img);
movieTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Child_Model child_model = child_modelList.get(position);
child_model.setExpanded(!child_model.getExpanded());
notifyItemChanged(getAdapterPosition());
}
});
ivEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position= getAdapterPosition();
if (customClickListener != null){
customClickListener.onItemClick(position);
}
}
});
}
}
}
I've been following this tutorial: Tutorial
To make a json recyclerviewer with onclick, but i wanted to use Fragments instead of activities.
I've figured everything out until the point of the onClick.
My problem is the setOnItemClickListener is not taking my getActivity()
I've tried so much, but i just cant see the bright light.
If anyone could help me out that would be totally awesome!
Me only real problem is that the getActivity is giving a red line in the:
fNieuwsAdapter.setOnItemClickListener(getActivity());
NieuwsFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import java.util.ArrayList;
public class NieuwsFragment extends Fragment implements NieuwsAdapter.OnItemClickListener {
public static final String EXTRA_URL = "nieuwsImageUrl";
public static final String EXTRA_HEADING = "nieuwsHeading";
public static final String EXTRA_CONTENT = "nieuwsContent";
private RecyclerView fNieuwsRecyclerView;
private NieuwsAdapter fNieuwsAdapter;
private ArrayList<NieuwsItem> fNieuwsList;
private RequestQueue fNieuwsQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nieuws, container, false);
fNieuwsRecyclerView = view.findViewById(R.id.recycler_view);
fNieuwsRecyclerView.setHasFixedSize(true);
fNieuwsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
fNieuwsList = new ArrayList<>();
fNieuwsQueue = Volley.newRequestQueue(getActivity());
parseJSON();
return view;
}
private void parseJSON() {
String url = "urlissecretsorry<3butthejsonparsingworks";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
public String nieuwsImageUrl;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
JSONArray attachArray = hit.getJSONArray("attachments");
for (int a = 0; a < attachArray.length(); a++) {
JSONObject attach = attachArray.getJSONObject(a);
nieuwsImageUrl = attach.getString("url");
}
String nieuwsHeading = hit.getString("title");
String nieuwsExcerpt = hit.getString("excerpt");
String nieuwsContent = hit.getString("content");
nieuwsExcerpt = html2text(nieuwsExcerpt);
fNieuwsList.add(new NieuwsItem(nieuwsImageUrl, nieuwsHeading, nieuwsExcerpt,nieuwsContent));
}
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList);
fNieuwsAdapter.setOnItemClickListener(getActivity());
fNieuwsRecyclerView.setAdapter(fNieuwsAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
fNieuwsQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(getActivity(), DetailActivity.class);
NieuwsItem clickedItem = fNieuwsList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
startActivity(detailIntent);
}
public String html2text(String html) {
try {
return Jsoup.parse(html).text();
} catch (Exception ignored) {
return "";
}
}
}
NieuwsItem.java
public class NieuwsItem {
private String nieuwsImageUrl;
private String nieuwsHeading;
private String nieuwsExcerpt;
private String nieuwsContent;
public NieuwsItem(String imageUrl, String heading, String excerpt, String content){
nieuwsImageUrl = imageUrl;
nieuwsHeading = heading;
nieuwsExcerpt = excerpt;
nieuwsContent = content;
}
public String getImageUrl(){
return nieuwsImageUrl;
}
public String getHeading(){
return nieuwsHeading;
}
public String getExcerpt(){
return nieuwsExcerpt;
}
public String getContent(){
return nieuwsContent;
}
}
NieuwsAdapter.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class NieuwsAdapter extends RecyclerView.Adapter<NieuwsAdapter.NieuwsViewHolder> {
private Context NieuwsContext;
private ArrayList<NieuwsItem> NieuwsList;
private OnItemClickListener NieuwsListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
NieuwsListener = listener;
}
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
#NonNull
#Override
public NieuwsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(NieuwsContext).inflate(R.layout.nieuws_item, parent, false);
return new NieuwsViewHolder(v);
}
#Override
public void onBindViewHolder(NieuwsViewHolder holder, int position) {
NieuwsItem currentitem = NieuwsList.get(position);
String ImageUrl = currentitem.getImageUrl();
String Heading = currentitem.getHeading();
String Excerpt = currentitem.getExcerpt();
holder.NieuwsTextViewHeading.setText(Heading);
holder.NieuwsTextViewExcerpt.setText(Excerpt);
Picasso.get().load(ImageUrl).fit().centerInside().into(holder.NieuwsImageView);
}
#Override
public int getItemCount() {
return NieuwsList.size();
}
public class NieuwsViewHolder extends RecyclerView.ViewHolder {
public ImageView NieuwsImageView;
public TextView NieuwsTextViewHeading;
public TextView NieuwsTextViewExcerpt;
public NieuwsViewHolder(#NonNull View itemView) {
super(itemView);
NieuwsImageView = itemView.findViewById(R.id.nieuws_image);
NieuwsTextViewHeading = itemView.findViewById(R.id.nieuws_heading);
NieuwsTextViewExcerpt = itemView.findViewById(R.id.nieuws_excerpt);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
}
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
String imageUrl = intent.getStringExtra("EXTRA_URL");
String creatorName = intent.getStringExtra("EXTRA_HEADING");
String likeCount = intent.getStringExtra("EXTRA_CONTENT");
ImageView imageView = findViewById(R.id.nieuws_detail_image);
TextView textViewHeading = findViewById(R.id.nieuws_detail_heading);
TextView textViewContent = findViewById(R.id.nieuws_detail_content);
Picasso.get().load(imageUrl).fit().centerInside().into(imageView);
textViewHeading.setText(creatorName);
textViewContent.setText("Likes: " + likeCount);
}
}
You cant use NieuwsAdapter.setOnItemClickListener(getActivity()); , unless your activity implements OnItemClickListener interface, but im seeing that your fragment implements OnItemClickListener, so you can use the fragment instead like this :
fNieuwsAdapter.setOnItemClickListener(NieuwsFragment.this);
And by the way, you are sending the data via intent with :
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
You have to get them with the same parameters (remove the ""):
String imageUrl = intent.getStringExtra(EXTRA_URL);
String creatorName = intent.getStringExtra(EXTRA_HEADING);
String likeCount = intent.getStringExtra(EXTRA_CONTENT);
Hope this helps
change
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
to
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist, OnItemClickListener mOnClickListener) {
this.NieuwsContext = context;
this.NieuwsList = nieuwslist;
this.NieuwsListener = mOnClickListener;
}
and this
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
change to
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwsListener.onItemClick(int position);
}
});
and then in fragment You can do it like this
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList,new NieuwsAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position)
{
//DoSomethingHere
}
});
I make an application, with CRUD function in Android using Room Database.
When i checked the checkbox like this, Error Pictures 1 i want that application show textview & edittext. But, after i press next button, it won't show textview & edittext based on checked in the checkbox Error Pictures 2 or textview & edittext showed up but that's not based by checkbox isChecked
This is the code :
AdapterTargetIbadah.java
package skripsi.com.ggr.managementibadah.adapter;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import skripsi.com.ggr.managementibadah.R;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class AdapterTargetIbadah extends RecyclerView.Adapter<AdapterTargetIbadah.ViewHolder>{
private ArrayList<Ibadah> targetIbadah;
private Context context;
private AppDatabase db;
public AdapterTargetIbadah(ArrayList<Ibadah> targets, Context ctx) {
targetIbadah = targets;
context = ctx;
db = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView tv_target;
EditText et_Target;
ViewHolder(View itemView) {
super(itemView);
tv_target = itemView.findViewById(R.id.tv_target);
et_Target = itemView.findViewById(R.id.et_Target);
}
}
#Override
public AdapterTargetIbadah.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_target, parent, false);
AdapterTargetIbadah.ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull AdapterTargetIbadah.ViewHolder holder, int position) {
Ibadah iba = targetIbadah.get(position);
if (iba.getTargetIbadah()!=null) {
holder.tv_target.setText(iba.getTargetIbadah());
iba.setEtTarget(holder.et_Target.getText().toString());
} else {
targetIbadah.remove(position);
}
}
#Override
public int getItemCount() {
return targetIbadah.size();
}
}
AdapterCheckboxTarget.java
package skripsi.com.ggr.managementibadah.adapter;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import skripsi.com.ggr.managementibadah.R;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class AdapterCheckboxTarget extends RecyclerView.Adapter<AdapterCheckboxTarget.ViewHolder> {
private ArrayList<Ibadah> targetIbadah;
private Context context;
private AppDatabase db;
public AdapterCheckboxTarget(ArrayList<Ibadah> targets, Context ctx) {
targetIbadah = targets;
context = ctx;
db = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
}
class ViewHolder extends RecyclerView.ViewHolder {
CheckBox cbTarget;
ViewHolder(View itemView) {
super(itemView);
cbTarget = itemView.findViewById(R.id.cbTarget);
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_targethome, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final String name = targetIbadah.get(position).getNamaIbadah();
holder.cbTarget.setText(name);
holder.cbTarget.setChecked(targetIbadah.get(position).getStatus());
holder.cbTarget.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (holder.cbTarget.isChecked()) {
targetIbadah.get(position).setStatus(true);
targetIbadah.get(position).setTargetIbadah(targetIbadah.get(position).getNamaIbadah());
Toast.makeText(context, "checklist", Toast.LENGTH_SHORT).show();
} else {
targetIbadah.get(position).setStatus(false);
Toast.makeText(context, "unchecklist", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public int getItemCount() {
return targetIbadah.size();
}
}
TargetHome.java ==> Activity using AdapterTargetIbadah.java
package skripsi.com.ggr.managementibadah;
import android.app.Activity;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import skripsi.com.ggr.managementibadah.adapter.AdapterCheckboxTarget;
import skripsi.com.ggr.managementibadah.adapter.AdapterTargetIbadah;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class TargetHome extends AppCompatActivity {
private AppDatabase db;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Ibadah> targetIbadah;
RecyclerView rvTarget;
Button btSimpan;
Context ctx;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.target_ibadah);
setTitle("Target Ibadah");
btSimpan = (Button)findViewById(R.id.btSimpanTarget);
targetIbadah = new ArrayList<>();
db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
rvTarget = findViewById(R.id.rvTar);
rvTarget.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvTarget.setLayoutManager(layoutManager);
targetIbadah.addAll(Arrays.asList(db.ibadahDAO().selectAllStatus()));
adapter = new AdapterTargetIbadah(targetIbadah, this);
rvTarget.setAdapter(adapter);
Ibadah ib = new Ibadah();
if (ib.getTargetIbadah()!=null) {
ib.setTvTarget(ib.getTargetIbadah());
ib.setEtTarget("");
db.ibadahDAO().insertCapai(ib);
}
btSimpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(MainActivity.getActIntent(TargetHome.this));
}
});
}
public static Intent getActIntent(Activity activity) {
// kode untuk pengambilan Intent
return new Intent(activity, TargetHome.class);
}
}
CheckboxTarget.java ==> Activity using AdapterCheckboxTarget
package skripsi.com.ggr.managementibadah;
import android.app.Activity;
import android.arch.persistence.room.Room;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import skripsi.com.ggr.managementibadah.adapter.AdapterCatatIbadah;
import skripsi.com.ggr.managementibadah.adapter.AdapterCheckboxTarget;
import skripsi.com.ggr.managementibadah.data.factory.AppDatabase;
import skripsi.com.ggr.managementibadah.model.Ibadah;
public class CheckboxTarget extends AppCompatActivity {
private AppDatabase db;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Ibadah> targetIbadah;
RecyclerView rvCb;
Button btNext;
Context ctx;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.target_home);
setTitle("Target Ibadah");
btNext = (Button) findViewById(R.id.btNextTarget);
targetIbadah = new ArrayList<>();
db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "ibadahdb").allowMainThreadQueries().build();
rvCb = findViewById(R.id.rvTarHome);
rvCb.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvCb.setLayoutManager(layoutManager);
targetIbadah.addAll(Arrays.asList(db.ibadahDAO().selectAllStatus()));
adapter = new AdapterCheckboxTarget(targetIbadah, this);
rvCb.setAdapter(adapter);
final Ibadah ibadah = (Ibadah) getIntent().getSerializableExtra("data");
if (ibadah != null) {
Ibadah ib = new Ibadah();
ib.setStatus(ib.status);
db.ibadahDAO().insertTarget(ib);
}
}
public static Intent getActIntent(Activity activity) {
// kode untuk pengambilan Intent
return new Intent(activity, CheckboxTarget.class);
}
}
Ibadah.java ==> Model
package skripsi.com.ggr.managementibadah.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import java.io.Serializable;
#Entity(tableName = "tibadah")
public class Ibadah implements Serializable {
#PrimaryKey(autoGenerate = true)
public int idIbadah;
#ColumnInfo(name = "nama_ibadah")
public String namaIbadah;
#ColumnInfo(name = "deskripsi_ibadah")
public String deskripsiIbadah;
#ColumnInfo(name = "target_ibadah")
public String targetIbadah;
#ColumnInfo(name = "tv_target")
public String tvTarget;
#ColumnInfo(name = "et_target")
public String etTarget;
#ColumnInfo(name = "et_capaian")
public String etCapaian;
#ColumnInfo(name = "status")
public boolean status;
public String getTvTarget() {
return tvTarget;
}
public void setTvTarget(String tvTarget) {
this.tvTarget = tvTarget;
}
public String getTargetIbadah() {
return targetIbadah;
}
public void setTargetIbadah(String targetIbadah) {
this.targetIbadah = targetIbadah;
}
public String getEtTarget() {
return etTarget;
}
public void setEtTarget(String etTarget) {
this.etTarget = etTarget;
}
public String getEtCapaian() {
return etCapaian;
}
public void setEtCapaian(String etCapaian) {
this.etCapaian = etCapaian;
}
public String getDeskripsiIbadah() {
return deskripsiIbadah;
}
public void setDeskripsiIbadah(String deskripsiIbadah) {
this.deskripsiIbadah = deskripsiIbadah;
}
public int getIdIbadah() {
return idIbadah;
}
public void setIdIbadah(int idIbadah) {
this.idIbadah = idIbadah;
}
public String getNamaIbadah() {
return namaIbadah;
}
public void setNamaIbadah(String namaIbadah) {
this.namaIbadah = namaIbadah;
}
public boolean getStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
I hope, you can help me. Thank you very much & sorry for my bad english.
First you have to set your TextView and EditText invisible in your XML, by adding android:visibility="invisible" to the XML of your TextView and EditText.
Then you have to use setVisibility(View.VISIBLE) after you have set the checkbox, like this:
yourcheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
//if checkbox is checked (b == true)
yourTextView.setVisibility(View.VISIBLE);
yourEditText.setVisibility(View.VISIBLE);
}
if (!b) {
//if checkbox is not checked (b == false)
yourTextView.setVisibility(View.INVISIBLE);
yourEditText.setVisibility(View.INVISIBLE);
}
}
});
If you first want to click a button and then check weather checkbox is checked, add this to your OnClickListenter:
if (yourcheckbox.isChecked) {
yourTextView.setVisibility(View.VISIBLE);
yourEditText.setVisibility(View.VISIBLE);
}
I'm creating a simple app that shows a list of item. Some of the item data is loaded in another thread, but when i scroll fast it shows the wrong data.
Here is the code for the adapter:
package com.lorenzorapetti.pokedex.adapter;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.lorenzorapetti.pokedex.R;
import com.lorenzorapetti.pokedex.Utils;
import com.lorenzorapetti.pokedex.model.PokemonSpecies;
import com.lorenzorapetti.pokedex.model.PokemonType;
import com.squareup.picasso.Picasso;
import org.apache.commons.lang3.StringUtils;
import java.lang.ref.WeakReference;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class PokemonSpeciesAdapter extends RecyclerView.Adapter<PokemonSpeciesAdapter.ViewHolder> {
private List<PokemonSpecies> mData;
private Context context;
public PokemonSpeciesAdapter(Context context, List<PokemonSpecies> data) {
this.context = context;
mData = data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView =((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.pokemon_species_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
PokemonSpecies item = mData.get(position);
holder.position = position;
Picasso.with(context)
.load(Utils.getSugimoriThumbUrl(item.getIdentifier()))
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(holder.image);
String identifier = "pokemon_species_" + Utils.convertIdentifier(item.getIdentifier())
+ "_name";
holder.textPrimary.setText(context.getResources().getString(
context.getResources().getIdentifier(identifier, "string", context.getPackageName())
));
holder.textSecondary.setText("#" + StringUtils.leftPad(item.getId().toString(), 3, "0"));
new AsyncLoad(item, holder, position).execute();
}
#Override
public int getItemCount() {
return mData != null ? mData.size() : 0;
}
#Override
public long getItemId(int position) {
return mData.get(position).getId();
}
public class ViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.pokemon_species_image) ImageView image;
#Bind(R.id.pokemon_species_name) TextView textPrimary;
#Bind(R.id.pokemon_species_number) TextView textSecondary;
#Bind(R.id.pokemon_species_primary_type)
TextView typePrimary;
#Bind(R.id.pokemon_species_secondary_type)
TextView typeSecondary;
int position;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
private class AsyncLoad extends AsyncTask<Void, Void, AsyncLoad.AsyncItem> {
private WeakReference<PokemonSpecies> itemData;
private WeakReference<ViewHolder> viewHolder;
private int mPosition;
public AsyncLoad(PokemonSpecies item, ViewHolder viewHolder, int position) {
this.itemData = new WeakReference<>(item);
this.viewHolder = new WeakReference<>(viewHolder);
mPosition = position;
}
#Override
protected AsyncLoad.AsyncItem doInBackground(Void... params) {
List<PokemonType> pokemonTypes = itemData.get().getDefaultPokemon().getPokemonTypes();
Log.d("App", "position: " + mPosition + ", holderPosition: " + viewHolder.get().position
+ ", pokemon: " + itemData.get().getIdentifier() + ", size: " + pokemonTypes.size());
String primaryIdentifier = "type_" +
Utils.convertIdentifier(pokemonTypes.get(0).getType().getIdentifier());
AsyncLoad.AsyncItem asyncItem = new AsyncLoad.AsyncItem();
asyncItem.primaryText = context.getResources().getString(
context.getResources().getIdentifier(primaryIdentifier + "_name", "string",
context.getPackageName()));
asyncItem.primaryColor = context.getResources().getColor(
context.getResources().getIdentifier(primaryIdentifier, "color",
context.getPackageName()));
if (pokemonTypes.size() == 2) {
String secondaryIdentifier = "type_" +
Utils.convertIdentifier(pokemonTypes.get(1).getType().getIdentifier());
asyncItem.secondaryText = context.getResources().getString(
context.getResources().getIdentifier(secondaryIdentifier + "_name", "string",
context.getPackageName()));
asyncItem.secondaryColor = context.getResources().getColor(
context.getResources().getIdentifier(secondaryIdentifier, "color",
context.getPackageName()));
}
return asyncItem;
}
#Override
protected void onPostExecute(AsyncLoad.AsyncItem asyncItem) {
ViewHolder holder = viewHolder.get();
if (mPosition == holder.position) {
holder.typePrimary.setText(asyncItem.primaryText);
holder.typePrimary.setBackgroundColor(asyncItem.primaryColor);
if (asyncItem.secondaryText != null) {
holder.typeSecondary.setText(asyncItem.secondaryText);
holder.typeSecondary.setBackgroundColor(asyncItem.secondaryColor);
}
}
}
protected class AsyncItem {
String primaryText;
int primaryColor;
String secondaryText;
int secondaryColor;
}
}
}
What can i do to load the exact data?