In my application i have custom adapter, adapter has image, and text when I scrolling the RecyclerView some items position automatic change
public class MyPhotosAdapter extends RecyclerView.Adapter<MyPhotosAdapter.ViewHolder> implements View.OnClickListener {
private PojoClasses.DashboardPhotos[] dashboardPhotoses;
private static final int TWEET_COMPOSER_REQUEST_CODE = 500;
Activity mActivity;
private ProgressDialog pDialog;
private static final String IMAGE_DIRECTORY_NAME = "My City Tag";
static File mediaFile;
static File mediaStorageDir;
static String mediaName = null;
static Integer twCurrent, fbCurrent;
ShareDialog shareDialog;
CallbackManager callbackManager;
private static final String CURRENT_USER_VIOLATION_ID = "twuserVId";
private static final String PREF_KEY_FACEBOOK_LOGIN = "facebook_loggedin";
private static final String PREF_KEY_TWITTER_LOGIN = "twitter_loggedin";
private static final String PREF_NAME = "my city tag";
private static SharedPreferences mSharedPreferences;
boolean isLoggedInTW;
boolean isLoggedInFB;
int isShareFb = 0;
DBHelper dbHelper;
public MyPhotosAdapter(PojoClasses.DashboardPhotos[] dashboardPhotoses) {
this.dashboardPhotoses = dashboardPhotoses;
}
public MyPhotosAdapter(Activity activity, PojoClasses.DashboardPhotos[] dashboardPhotoses) {
this.dashboardPhotoses = dashboardPhotoses;
mActivity = activity;
}
// Create new views (invoked by the layout manager)
#Override
public MyPhotosAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
FacebookSdk.sdkInitialize(mActivity);
callbackManager = CallbackManager.Factory.create();
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY,TWITTER_SECRET);
Fabric.with(mActivity, new com.twitter.sdk.android.Twitter(authConfig));
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_photo, null);
dbHelper = new DBHelper(mActivity);
Fabric.with(mActivity, new TweetComposer());
shareDialog=new ShareDialog(mActivity);
/* Initialize application preferences */
mSharedPreferences = mActivity.getSharedPreferences(PREF_NAME, 0);
isLoggedInFB = mSharedPreferences.getBoolean(PREF_KEY_FACEBOOK_LOGIN, false);
isLoggedInTW = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
viewHolder.mImageViewCapUser.setImageBitmap(dashboardPhotoses[position].getThumbnail());
viewHolder.txtDescription.setText(dashboardPhotoses[position].getDescription());
viewHolder.txtDate.setText(dashboardPhotoses[position].getCreatedDate());
viewHolder.txtViolation.setText(dashboardPhotoses[position].getViolation());
final int FB = dashboardPhotoses[position].getIsShareFb();
final int TW = dashboardPhotoses[position].getIsShareTw();
final int priority = dashboardPhotoses[position].getPriority();
switch (priority) {
case 2:
viewHolder.mImageViewPriority.setBackgroundColor(Color.parseColor("#D50000"));
break;
case 3:
viewHolder.mImageViewPriority.setBackgroundColor(Color.parseColor("#FF9800"));
break;
case 4:
viewHolder.mImageViewPriority.setBackgroundColor(Color.parseColor("#FFEB3B"));
break;
}
viewHolder.mImageViewIcon.setTag(dashboardPhotoses[position]);
if (FB == 0) {
viewHolder.mImageViewIcon.setImageResource(R.drawable.ic_action_share);
viewHolder.mImageViewIcon.setFocusable(false);
viewHolder.mImageViewIcon.setFocusableInTouchMode(false);
viewHolder.mImageViewIcon.setClickable(true);
viewHolder.mImageViewIcon.setOnClickListener(this);
} else if (TW == 0) {
viewHolder.mImageViewIcon.setImageResource(R.drawable.ic_action_share);
viewHolder.mImageViewIcon.setFocusable(false);
viewHolder.mImageViewIcon.setFocusableInTouchMode(false);
viewHolder.mImageViewIcon.setClickable(true);
viewHolder.mImageViewIcon.setOnClickListener(this);
} else {
viewHolder.mImageViewIcon.setImageResource(R.mipmap.ic_send);
}
viewHolder.txtDescription.setTag(dashboardPhotoses[position]);
if (FB == 0) {
viewHolder.txtDescription.setFocusable(false);
viewHolder.txtDescription.setFocusableInTouchMode(false);
viewHolder.txtDescription.setClickable(true);
viewHolder.txtDescription.setOnClickListener(this);
} else if (TW == 0) {
viewHolder.txtDescription.setFocusable(false);
viewHolder.txtDescription.setFocusableInTouchMode(false);
viewHolder.txtDescription.setClickable(true);
viewHolder.txtDescription.setOnClickListener(this);
} else {
}
}
#Override
public void onClick(View v) {
PojoClasses.DashboardPhotos dashboardPhotos;
switch (v.getId()){
case R.id.imgv_Icon_list:
dashboardPhotos = (PojoClasses.DashboardPhotos) v.getTag();
int fb = dashboardPhotos.getIsShareFb();
int tw = dashboardPhotos.getIsShareTw();
if(fb == 0 && tw == 0) {
selectSocial(dashboardPhotos);
}
else if(fb == 0){
selectSocialfb(dashboardPhotos);
}
else if(tw == 0){
selectSocialtw(dashboardPhotos);
}
break;
case R.id.txt_tag_des:
dashboardPhotos = (PojoClasses.DashboardPhotos) v.getTag();
Intent i = new Intent(mActivity,EditViolationActivity.class);
i.putExtra("UserViolationId",dashboardPhotos.getUserViolationId());
mActivity.startActivity(i);
break;
}
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
public static TextView txtDescription;
public ImageView mImageViewCapUser;
public TextView txtDate;
public TextView txtViolation;
public static ImageView mImageViewIcon;
public View mImageViewPriority;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtDescription = (TextView) itemLayoutView.findViewById(R.id.txt_tag_des);
txtDate = (TextView) itemLayoutView.findViewById(R.id.txt_date);
txtViolation = (TextView) itemLayoutView.findViewById(R.id.txt_violation);
mImageViewCapUser = (ImageView) itemLayoutView.findViewById(R.id.imgv_capture_user);
mImageViewIcon = (ImageView) itemLayoutView.findViewById(R.id.imgv_Icon_list);
mImageViewPriority = itemLayoutView.findViewById(R.id.imgv_priority);
}
}
#Override
public int getItemCount() {
return dashboardPhotoses.length;
}
}
Please help me if anyone have solution for that particular problem .
Thanks in advance
Put a default in your switch statement
default:
viewHolder.mImageViewPriority.setBackgroundColor("Default color here for other priorities");
break;
and put default values in else part of all your if else conditions
Related
I have a problem when working with nested RecyclerView in RecyclerView. In my parent RecyclerView I am displaying rows of items. These rows have rows of scanned goods. If I want to display the scanned rows, I click on the parent Recyclerview and it expands. When I tap on the child RecyclerView, it should show edit/delete buttons instead of an error message. Notify works until I shrink the parent RecyclerView(tap it again) and expand it again. At the moment notify does not trigger onBindViewHolder.
Anyone know what to do?
Parent Fragment
public class ShowCdlFragment extends Fragment {
private FragmentShowCdlBinding binding;
private Resources res;
private SessionManager session;
private Bundle params;
private F1002dlh f1002dlh;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.binding = FragmentShowCdlBinding.inflate(getLayoutInflater());
this.session = new SessionManager(getContext());
this.res = getResources();
this.session.checkLogin(getActivity());
// Inflate the layout for this fragment
return this.binding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.params = getArguments();
this.f1002dlh = this.params.getParcelable("F1002DLH");
RecyclerView rvMenu = (RecyclerView) binding.showCdlRecyclerView;
ArrayList<F1002dlr> f1002dlrArrayList = this.f1002dlh.getF1002dlh_f1002dlrs();
CdlAdapter cdlAdapter = new CdlAdapter(f1002dlrArrayList, getContext());
rvMenu.setAdapter(cdlAdapter);
rvMenu.setLayoutManager(new LinearLayoutManager(this.getContext()));
}
}
Parent Adapter
public class CdlAdapter extends RecyclerView.Adapter<CdlAdapter.ViewHolder> {
private List<F1002dlr> f1002dlrList;
private Context context;
private Integer expandedPosition = -1;
private RecyclerView.RecycledViewPool recycledViewPool;
private RecyclerView cdlItem_sub_recyclerView;
public CdlAdapter(List<F1002dlr> f1002dlrList, Context context) {
this.f1002dlrList = f1002dlrList;
this.context = context;
this.recycledViewPool = new RecyclerView.RecycledViewPool();
}
#NonNull
#Override
public CdlAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View cdlView = inflater.inflate(R.layout.cdl_item, parent, false);
return new ViewHolder(cdlView);
}
#Override
public void onBindViewHolder(#NonNull CdlAdapter.ViewHolder holder, int position) {
F1002dlr f1002dlr = f1002dlrList.get(position);
ImageView f1002dlr_status_imageView = holder.f1002dlr_status_imageView;
TextView f1002dlr_vpd_textView = holder.f1002dlr_vpd_textView;
TextView f1002dlr_radek_textView = holder.f1002dlr_radek_textView;
TextView f1002dlr_komodita_textView = holder.f1002dlr_komodita_textView;
TextView f1002dlr_xvyr_textView = holder.f1002dlr_xvyr_textView;
TextView f1002dlr_jakost_textView = holder.f1002dlr_jakost_textView;
TextView f1002dlr_mnozstvi_textView = holder.f1002dlr_mnozstvi_textView;
TextView f1002dlr_vady_textView = holder.f1002dlr_vady_textView;
TextView f1002dlr_mj_textView = holder.f1002dlr_mj_textView;
TextView f1002dlr_hodnota_textView = holder.f1002dlr_hodnota_textView;
TextView f1002dlr_pc_textView = holder.f1002dlr_pc_textView;
f1002dlr_status_imageView.setImageResource(getImageId(f1002dlr.getStatus()));
f1002dlr_vpd_textView.setText(f1002dlr.getF1002dlr_vpd().toString());
f1002dlr_radek_textView.setText(f1002dlr.getF1002dlr_radek().toString());
f1002dlr_komodita_textView.setText(f1002dlr.getF1002dlr_komodita());
f1002dlr_xvyr_textView.setText(f1002dlr.getF1002dlr_xvyr().toString());
f1002dlr_jakost_textView.setText(f1002dlr.getF1002dlr_jakost());
f1002dlr_mnozstvi_textView.setText(String.format("%.2f", f1002dlr.getF1002dlr_mnozstvi()));
f1002dlr_vady_textView.setText(f1002dlr.getF1002dlr_vady().toString());
f1002dlr_mj_textView.setText(f1002dlr.getF1002dlr_mj());
f1002dlr_hodnota_textView.setText(String.format("%.2f", f1002dlr.getHodnota()));
f1002dlr_pc_textView.setText(String.format("%.2f", f1002dlr.getF1002dlr_pc()));
Double mnozstvi = 0.00;
Integer vady = 0;
for (F1002ck_data f1002ck_data : f1002dlr.getF1002dlr_f1002ck_datas()) {
mnozstvi += f1002ck_data.getF1002ck_data_mnozstvi_mj1();
vady += f1002ck_data.getF1002ck_data_vady();
}
TextView nasnimane_mnozstvi_textView = holder.nasnimane_mnozstvi_textView;
TextView nasnimane_vady_textView = holder.nasnimane_vady_textView;
nasnimane_mnozstvi_textView.setText(String.format("%.2f", mnozstvi));
nasnimane_vady_textView.setText(vady.toString());
if (expandedPosition == -1) {
f1002dlr.setExpanded(false);
}
Boolean isExpanded = f1002dlr.getExpanded();
if (isExpanded) {
holder.expandable_constraintLayout.setVisibility(View.VISIBLE);
} else {
holder.expandable_constraintLayout.setVisibility(View.GONE);
}
cdlItem_sub_recyclerView = holder.cdlItem_sub_recyclerView;
LinearLayoutManager layoutManager = new LinearLayoutManager(cdlItem_sub_recyclerView.getContext(), LinearLayoutManager.VERTICAL, false);
cdlItem_sub_recyclerView.setLayoutManager(layoutManager);
cdlItem_sub_recyclerView.setAdapter(new CdlSubAdapter(f1002dlr.getF1002dlr_f1002ck_datas(), context));
cdlItem_sub_recyclerView.setRecycledViewPool(recycledViewPool);
}
private void updateF1002dlh() {
if (context instanceof AdapterCallInterface) {
((AdapterCallInterface) context).setDocumentData(f1002dlrList);
}
}
private int getImageId(int status) {
Integer imageId = 0;
switch (status) {
case -2:
imageId = R.drawable.orange_status;
break;
case -1:
imageId = R.drawable.red_status;
break;
case 0:
imageId = R.drawable.grey_status;
break;
case 1:
imageId = R.drawable.green_status;
break;
}
return imageId;
}
#Override
public int getItemCount() {
return f1002dlrList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView f1002dlr_status_imageView;
private TextView f1002dlr_vpd_textView;
private TextView f1002dlr_radek_textView;
private TextView f1002dlr_komodita_textView;
private TextView f1002dlr_xvyr_textView;
private TextView f1002dlr_jakost_textView;
private TextView f1002dlr_mnozstvi_textView;
private TextView f1002dlr_vady_textView;
private TextView f1002dlr_mj_textView;
private TextView f1002dlr_hodnota_textView;
private TextView f1002dlr_pc_textView;
private TextView nasnimane_mnozstvi_textView;
private TextView nasnimane_vady_textView;
private LinearLayout linearLayout;
private ConstraintLayout main_constrainLayout;
private ConstraintLayout expandable_constraintLayout;
private ConstraintLayout second_constraintLayout;
private RecyclerView cdlItem_sub_recyclerView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
initAdapterViews();
second_constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
F1002dlr f1002dlr;
if (expandedPosition >= 0 && expandedPosition != getAdapterPosition()) {
int prev = expandedPosition;
f1002dlr = f1002dlrList.get(prev);
if (f1002dlr.getExpanded()) {
f1002dlr.setExpanded(!f1002dlr.getExpanded());
notifyItemChanged(prev);
}
}
expandedPosition = getAdapterPosition();
f1002dlr = f1002dlrList.get(expandedPosition);
f1002dlr.setExpanded(!f1002dlr.getExpanded());
updateF1002dlh();
notifyItemChanged(expandedPosition);
}
});
}
private void initAdapterViews() {
f1002dlr_status_imageView = (ImageView) itemView.findViewById(R.id.cdlItem_status_imageView);
f1002dlr_vpd_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_vpd_textView);
f1002dlr_radek_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_radek_textView);
f1002dlr_komodita_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_komodita_textView);
f1002dlr_xvyr_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_xvyr_textView);
f1002dlr_jakost_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_jakost_textView);
f1002dlr_mnozstvi_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_mnozstvi_textView);
f1002dlr_vady_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_vady_textView);
f1002dlr_mj_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_mj_textView);
f1002dlr_hodnota_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_hodnota_textView);
f1002dlr_pc_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_pc_textView);
nasnimane_mnozstvi_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_nasnimane_mnozstvi_textView);
nasnimane_vady_textView = (TextView) itemView.findViewById(R.id.cdlItem_value_nasnimane_vady_textView);
linearLayout = (LinearLayout) itemView.findViewById(R.id.menuItem_linearLayout);
main_constrainLayout = (ConstraintLayout) itemView.findViewById(R.id.cdlItem_main_constraintLayout);
expandable_constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.cdlItem_expandable_constraintLayout);
second_constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.cdlItem_second_constraintLayout);
cdlItem_sub_recyclerView = (RecyclerView) itemView.findViewById(R.id.cdlItem_sub_recyclerView);
}
}
}
Child Adapter
public class CdlSubAdapter extends RecyclerView.Adapter<CdlSubAdapter.ViewHolder> {
private List<F1002ck_data> f1002ck_dataList;
private Context context;
private Integer showingButtonsPosition = -1;
public CdlSubAdapter(List<F1002ck_data> f1002ck_dataList, Context context) {
this.context = context;
this.f1002ck_dataList = f1002ck_dataList;
}
#NonNull
#Override
public CdlSubAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View cdSublView = inflater.inflate(R.layout.cdl_sub_item, parent, false);
return new ViewHolder(cdSublView);
}
#Override
public void onBindViewHolder(#NonNull CdlSubAdapter.ViewHolder holder, int position) {
F1002ck_data f1002ck_data = f1002ck_dataList.get(position);
ImageView f1002ck_data_status_imageView = holder.f1002ck_data_status_imageView;
if (!Objects.equals(f1002ck_data.getF1002ck_data_indikace(), Funkce.INDIKACE_OK)) {
f1002ck_data.setStatus(Funkce.STATUS_WRONG);
}
f1002ck_data_status_imageView.setImageResource(getImageId(f1002ck_data.getStatus()));
ConstraintLayout cdlSubItem_chyba_constrainLayout = holder.cdlSubItem_chyba_constrainLayout;
TextView nazev_zbozi = holder.nazev_zbozi;
TextView f1002ck_data_id_zbozi = holder.f1002ck_data_id_zbozi;
TextView f1002ck_data_cislodokl = holder.f1002ck_data_cislodokl;
TextView f1002ck_data_mnozstvi_mj1 = holder.f1002ck_data_mnozstvi_mj1;
TextView f1002ck_data_vady = holder.f1002ck_data_vady;
TextView chyba = holder.chyba;
nazev_zbozi.setText(f1002ck_data.getNazevZbozi());
f1002ck_data_id_zbozi.setText(f1002ck_data.getF1002ck_data_id_f10zbozi().toString());
f1002ck_data_cislodokl.setText(f1002ck_data.getF1002ck_data_cislodokl().toString());
f1002ck_data_mnozstvi_mj1.setText(String.format("%.2f", f1002ck_data.getF1002ck_data_mnozstvi_mj1()));
f1002ck_data_vady.setText(f1002ck_data.getF1002ck_data_vady().toString());
chyba.setText(f1002ck_data.getF1002ck_data_chyba());
LinearLayout buttons_linearLayout = holder.buttons_linearLayout;
if (showingButtonsPosition == -1) {
f1002ck_data.setShowButtons((short) View.GONE);
}
if (f1002ck_data.getShowButtons() == View.VISIBLE) {
cdlSubItem_chyba_constrainLayout.setVisibility(View.GONE);
buttons_linearLayout.setVisibility((int) f1002ck_data.getShowButtons());
} else {
cdlSubItem_chyba_constrainLayout.setVisibility(View.VISIBLE);
buttons_linearLayout.setVisibility((int) f1002ck_data.getShowButtons());
}
}
private int getImageId(int status) {
Integer imageId = 0;
switch (status) {
case -2:
imageId = R.drawable.orange_status;
break;
case -1:
imageId = R.drawable.red_status;
break;
case 0:
imageId = R.drawable.grey_status;
break;
case 1:
imageId = R.drawable.green_status;
break;
}
return imageId;
}
private Integer sortElementsInList(F1002ck_data f1002ck_data) {
Collections.sort(f1002ck_dataList, new Comparator<F1002ck_data>() {
#Override
public int compare(F1002ck_data t1, F1002ck_data t2) {
if (t1.getStatus().compareTo(t2.getStatus()) == 0) {
return t1.getF1002ck_data_id_f10zbozi().compareTo(t2.getF1002ck_data_id_f10zbozi());
}
return t1.getStatus().compareTo(t2.getStatus());
}
});
for (int i = 0; i < f1002ck_dataList.size(); i++) {
if (f1002ck_data.equals(f1002ck_dataList.get(i))) {
return i;
}
}
return 0;
}
private void updateF1002dlh() {
if (context instanceof AdapterCallInterface) {
((AdapterCallInterface) context).setF1002ck_data(f1002ck_dataList);
}
}
private void removeRowF1002ck_data(F1002ck_data f1002ck_data) {
if (context instanceof AdapterCallInterface) {
((AdapterCallInterface) context).removeRowF1002ck_data(f1002ck_data);
}
}
#Override
public void onViewAttachedToWindow(#NonNull ViewHolder holder) {
super.onViewAttachedToWindow(holder);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull List<Object> payloads) {
super.onBindViewHolder(holder, position, payloads);
}
#Override
public int getItemCount() {
return f1002ck_dataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout linearLayout;
private ImageView f1002ck_data_status_imageView;
private ConstraintLayout cdlSubItem_chyba_constrainLayout;
private TextView nazev_zbozi;
private TextView f1002ck_data_id_zbozi;
private TextView f1002ck_data_cislodokl;
private TextView f1002ck_data_mnozstvi_mj1;
private TextView f1002ck_data_vady;
private TextView chyba;
private LinearLayout buttons_linearLayout;
private CardView edit_imageButton;
private CardView remove_imageButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
initAdapterViews();
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
F1002ck_data f1002ck_data = null;
if (showingButtonsPosition >= 0 && showingButtonsPosition != getAdapterPosition()) {
int prev = showingButtonsPosition;
f1002ck_data = f1002ck_dataList.get(prev);
if (f1002ck_data.getShowButtons() == (short) View.VISIBLE) {
f1002ck_data.setShowButtons((short) View.GONE);
notifyItemChanged(prev);
}
}
showingButtonsPosition = getAdapterPosition();
if (!f1002ck_dataList.isEmpty()) {
f1002ck_data = f1002ck_dataList.get(showingButtonsPosition);
}
if (f1002ck_data != null) {
if (f1002ck_data.getShowButtons() == (short) View.VISIBLE) {
f1002ck_data.setShowButtons((short) View.GONE);
//cdlSubItem_chyba_constrainLayout.setVisibility(View.GONE);
//buttons_linearLayout.setVisibility((int) f1002ck_data.getShowButtons());
} else {
f1002ck_data.setShowButtons((short) View.VISIBLE);
//cdlSubItem_chyba_constrainLayout.setVisibility(View.VISIBLE);
//buttons_linearLayout.setVisibility((int) f1002ck_data.getShowButtons());
}
}
notifyItemChanged(showingButtonsPosition);
}
});
edit_imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
F1002ck_data f1002ck_data = f1002ck_dataList.get(position);
f1002ck_data.setStatus(Funkce.STATUS_OK);
f1002ck_data_status_imageView.setImageResource(getImageId(f1002ck_data.getStatus()));
showingButtonsPosition = sortElementsInList(f1002ck_data);
updateF1002dlh();
notifyDataSetChanged();
}
});
remove_imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
F1002ck_data f1002ck_data = f1002ck_dataList.get(position);
f1002ck_dataList.remove(f1002ck_data);
removeRowF1002ck_data(f1002ck_data);
notifyItemRemoved(position);
}
});
}
private void initAdapterViews() {
linearLayout = (LinearLayout) itemView.findViewById(R.id.cdlSubItem_linearLayout);
f1002ck_data_status_imageView = (ImageView) itemView.findViewById(R.id.cdlSubItem_status_imageView);
cdlSubItem_chyba_constrainLayout = (ConstraintLayout) itemView.findViewById(R.id.cdlSubItem_chyba_constraintLayout);
nazev_zbozi = (TextView) itemView.findViewById(R.id.cdlSubItem_value_nazev_zbozi_textView);
f1002ck_data_id_zbozi = (TextView) itemView.findViewById(R.id.cdlSubItem_value_id_f10zbozi_textView);
f1002ck_data_cislodokl = (TextView) itemView.findViewById(R.id.cdlSubItem_value_cislodokl_textView);
f1002ck_data_mnozstvi_mj1 = (TextView) itemView.findViewById(R.id.cdlSubItem_value_mnozstvi_mj1_textView);
f1002ck_data_vady = (TextView) itemView.findViewById(R.id.cdlSubItem_value_vady_textView);
chyba = (TextView) itemView.findViewById(R.id.cdlSubItem_value_chyba_textView);
buttons_linearLayout = (LinearLayout) itemView.findViewById(R.id.cdlSubItem_buttons_linearLayout);
edit_imageButton = (CardView) itemView.findViewById(R.id.cdlSubItem_edit_cardView);
remove_imageButton = (CardView) itemView.findViewById(R.id.cdlSubItem_remove_cardView);
}
}
}
Updated
In the course of this question, I made several changes inside the child adapter.
Actually this screen displays a set of questions and the task is to read the user entered or selected answer.
So the my question is, how to get the value from ChooseAdapter to QuestionAdapter and then get all the value from QuestionAdapter to my Activity.
My english is little bit weak, sorry for that.
And thanks in advance.
Main adapter : QuestionAdapter.java
public class QuestionsAdapter extends RecyclerView.Adapter<QuestionsAdapter.RecyclerViewHolder> {
private ArrayList<Question> mRecyclerViewItems;
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final String TAG = QuestionsAdapter.class.getSimpleName();
private static Context mContext;
private NetworkManager nm;
private boolean visibility = false;
private ChoiceAdapter adapter;
private ArrayList<QuestionsAnswer> questionsAnswers = new ArrayList<>();
ArrayList<ChoiceAnswer> choiceAnswers;
public QuestionsAdapter(Context context, ArrayList<Question> recyclerViewItems) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//this view contains recycler view under recycler view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
default:
final RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder;
Question data = (Question) mRecyclerViewItems.get(position);
try {
recyclerViewHolder.txtQuestion.setText(data.getQuestion());
recyclerViewHolder.txtQuestionType.setText(data.getQuestionType());
if (data.getQuestionType().equals("MULT")) {
recyclerViewHolder.mRecyclerChoice.setVisibility(View.VISIBLE);
recyclerViewHolder.edtQuestion.setVisibility(View.GONE);
if (data.getChoices().size() > 0) {
adapter = new ChoiceAdapter(mContext, data.getChoices(), position);
recyclerViewHolder.mRecyclerChoice.setAdapter(adapter);
}
} else {
recyclerViewHolder.mRecyclerChoice.setVisibility(View.GONE);
recyclerViewHolder.edtQuestion.setVisibility(View.VISIBLE);
}
recyclerViewHolder.btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (data.getQuestionType().equals("MULT")) {
Log.v(TAG, "array Data : " + adapter.getChoiceAnswer());
} else {
Log.v(TAG, "array Data : " + recyclerViewHolder.edtQuestion.getText().toString());
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView txtQuestion,txtQuestionType;
EditText edtQuestion;
RecyclerView mRecyclerChoice;
Button btnOk;
private LinearLayoutManager linearLayoutManager;
public RecyclerViewHolder(View view) {
super(view);
txtQuestion = view.findViewById(R.id.txt_question);
edtQuestion = view.findViewById(R.id.edt_question);
mRecyclerChoice = view.findViewById(R.id.recycler_choice);
btnOk = view.findViewById(R.id.btn_ok);
txtQuestionType = view.findViewById(R.id.txt_question_type);
initRecyclerView();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtQuestionType.getText().toString().equals("MULT")) {
Log.v(TAG, "array Data : " + adapter.getChoiceAnswer());
} else {
Log.v(TAG, "array Data : " + edtQuestion.getText().toString());
}
}
});
}
private void initRecyclerView() {
//setting properties of recyclerView
mRecyclerChoice.setHasFixedSize(true);
mRecyclerChoice.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(mContext);
mRecyclerChoice.setLayoutManager(linearLayoutManager);
}
}
public static void validation() {
Toast.makeText(mContext, "testing", Toast.LENGTH_SHORT).show();
}}
for list of CheckBox : ChooseAdapter.java
public class ChoiceAdapter extends RecyclerView.Adapter<ChoiceAdapter.RecyclerViewHolder> {
private ArrayList<Choice> mRecyclerViewItems;
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final String TAG = ChoiceAdapter.class.getSimpleName();
private Context mContext;
private NetworkManager nm;
// private OnItemClickListener mOnItemClickListener;
private boolean visibility = false;
private static ArrayList<ChoiceAnswer> choiceAnswerArrayList;
private ChoiceAnswer choiceAnswer;
String arrayData;
public ChoiceAdapter(Context context, ArrayList<Choice> recyclerViewItems, int position) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
// choiceAnswer.key = 0;
choiceAnswerArrayList = new ArrayList<>();
//initializing choiceAnswer
choiceAnswer = new ChoiceAnswer();
choiceAnswer.values = new ArrayList<>();
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//this view contains recycler view under recycler view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio_button, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
default:
final RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder;
Choice data = (Choice) mRecyclerViewItems.get(position);
try {
recyclerViewHolder.checkChoice.setText(data.getChoiceName());
recyclerViewHolder.checkChoice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
arrayData = "";
for (int i = 0; i < mRecyclerViewItems.size(); i++) {
if (isChecked) {
if (!choiceAnswer.values.contains(data.getChoiceID())) {
choiceAnswer.values.add(i, data.getChoiceID());
}
} else {
choiceAnswer.values.remove(data.getChoiceID());
// arrayData = choiceAnswer.values.toString().replace("[", "").replace("]", "").trim();
}
try {
arrayData = arrayData + "," + choiceAnswer.values.get(i);
}catch (IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public String getChoiceAnswer() {
return arrayData;
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
CheckBox checkChoice;
public RecyclerViewHolder(View view) {
super(view);
checkChoice = view.findViewById(R.id.check_choice);
}
}}
Please help me guys I am trying this since last 3 days...
I've implemented my own login too, but it didn't working properly.
My datetime is currently stored as UNIX time stamp. I want to display it as h:mm a in my Recyclerview.
Where should I convert the UNIX time stamp into normal time in the RecyclerView Adapter/Viewholder (in terms of the best performance)?
Should I do it in the getItemViewType(int position) of the RecyclerView.Adapter, or the onBindViewHolder or the bind function of the ViewHolder class?
Edit: My code
public class ChatListAdapter extends RecyclerView.Adapter {
private final LayoutInflater mInflater;
private List<Chat> mChats;
private final String ownerMe = "OWNER_ME";
private static final int VIEW_TYPE_MESSAGE_ME = 1;
private static final int VIEW_TYPE_MESSAGE_ME_CORNER = 2;
private static final int VIEW_TYPE_MESSAGE_BF = 3;
private static final int VIEW_TYPE_MESSAGE_BF_CORNER = 4;
ChatListAdapter(Context context) {mInflater = LayoutInflater.from(context);}
#Override
public int getItemViewType(int position) {
Chat chat = mChats.get(position);
if(chat.getUser().equals(ownerMe)) {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_ME;
} else {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
} else {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_BF;
} else {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType == VIEW_TYPE_MESSAGE_ME || viewType == VIEW_TYPE_MESSAGE_ME_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_right, parent, false);
return new MeMessageHolder(view);
} else if (viewType == VIEW_TYPE_MESSAGE_BF || viewType == VIEW_TYPE_MESSAGE_BF_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_left, parent, false);
return new BfMessageHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (mChats != null) {
Chat current = mChats.get(position);
long unixTime= current.getUnixTime();
Date time = new java.util.Date(unixTime*1000L);
SimpleDateFormat sdf = new java.text.SimpleDateFormat("h:mm a");
String formattedTime = sdf.format(time);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_ME:
((MeMessageHolder) holder).bind(current, formattedTime, false);
break;
case VIEW_TYPE_MESSAGE_ME_CORNER:
((MeMessageHolder) holder).bind(current, formattedTime, true);
break;
case VIEW_TYPE_MESSAGE_BF:
((BfMessageHolder) holder).bind(current, formattedTime, false);
break;
case VIEW_TYPE_MESSAGE_BF_CORNER:
((BfMessageHolder) holder).bind(current, formattedTime, true);
break;
}
}
}
class MeMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerRightIImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private MeMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerRightIImageView = itemView.findViewById(R.id.corner_view_right);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, String formattedTime, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(formattedTime);
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v2);
} else {
cornerRightIImageView.setVisibility(View.INVISIBLE);
}
}
}
class BfMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerLeftImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private BfMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerLeftImageView = itemView.findViewById(R.id.corner_view_left);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, String formattedTime, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(formattedTime);
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v3);
} else {
cornerLeftImageView.setVisibility(View.INVISIBLE);
}
}
}
void setChats(List<Chat> chats) {
mChats = chats;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if(mChats!=null)
return mChats.size();
else return 0;
}
}
This is method correct? I formatted the date in the onBindViewHoldermethod
It depends whether you want to display different dates on different items of the recyclerview, or the same date on all items of the recyclerview.
If you want to show same date to all items, better to do it outside of the adapter and then pass the parsed date to the recyclerview adapter.
Or, if you want to show different dates on each item, you should do it inside onBindViewHolder as it has access to the item position.
Remember, getItemViewType is used for getting a view type out of the available ones. This is used in case you are inflating multiple views. Think of a chatapp where view1 will display message on the left, and view2 will display message on the right; all within the same recyclerview.
The onBindViewHolder method simply performs a generic binding task. Binds what : the item of the inflated view and the data.
It seems like business logic. So, i recommend to move you UNIX time stamp convertation in Model for example.
class Chat {
private Long unixTime;
// another code
public Long getUnixTime() {
return unixTime;
}
public String convertedUnixTimeToString(String format) {
// Also need to add some format validation
if(format == null) {
// do some action, like trowing exception, or setting default value in format
}
Date time = new java.util.Date(unixTime*1000L);
SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
return sdf.format(time);
}
}
I recommend you to use JodaTime for date&time formatting. Very useful thing.
And then, just modify your code
public class ChatListAdapter extends RecyclerView.Adapter {
private final LayoutInflater mInflater;
private List<Chat> mChats;
private final String ownerMe = "OWNER_ME";
private static final int VIEW_TYPE_MESSAGE_ME = 1;
private static final int VIEW_TYPE_MESSAGE_ME_CORNER = 2;
private static final int VIEW_TYPE_MESSAGE_BF = 3;
private static final int VIEW_TYPE_MESSAGE_BF_CORNER = 4;
ChatListAdapter(Context context) {mInflater = LayoutInflater.from(context);}
#Override
public int getItemViewType(int position) {
Chat chat = mChats.get(position);
if(chat.getUser().equals(ownerMe)) {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_ME;
} else {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
} else {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_BF;
} else {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType == VIEW_TYPE_MESSAGE_ME || viewType == VIEW_TYPE_MESSAGE_ME_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_right, parent, false);
return new MeMessageHolder(view);
} else if (viewType == VIEW_TYPE_MESSAGE_BF || viewType == VIEW_TYPE_MESSAGE_BF_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_left, parent, false);
return new BfMessageHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (mChats != null) {
Chat current = mChats.get(position);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_ME:
((MeMessageHolder) holder).bind(current, false);
break;
case VIEW_TYPE_MESSAGE_ME_CORNER:
((MeMessageHolder) holder).bind(current, true);
break;
case VIEW_TYPE_MESSAGE_BF:
((BfMessageHolder) holder).bind(current, false);
break;
case VIEW_TYPE_MESSAGE_BF_CORNER:
((BfMessageHolder) holder).bind(current, true);
break;
}
}
}
class MeMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerRightIImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private MeMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerRightIImageView = itemView.findViewById(R.id.corner_view_right);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(chat.convertedUnixTimeToString("h:mm a"));
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v2);
} else {
cornerRightIImageView.setVisibility(View.INVISIBLE);
}
}
}
class BfMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerLeftImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private BfMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerLeftImageView = itemView.findViewById(R.id.corner_view_left);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(chat.convertedUnixTimeToString("h:mm a"));
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v3);
} else {
cornerLeftImageView.setVisibility(View.INVISIBLE);
}
}
}
void setChats(List<Chat> chats) {
mChats = chats;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if(mChats!=null)
return mChats.size();
else return 0;
}
}
You should be updating the UI changes in onBindViewHolder method. You can call bind method of ViewHolder in onBindViewHolder.
Example:
public class SampleAdapter extends RecyclerView.Adapter<SampleAdapter.ViewHolder> {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.sample_view, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
viewHolder.bind(i);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(#NonNull View itemView) {
super(itemView);
}
void bind(int position) {
// Do your data updates here.
}
}
}
Just Use SimpleDateFormat with yyyy-MM-dd pattern .
Apply SimpleDateFormat.format(millis) in onBindViewHolder method of RecyclerView.
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
then first you need to convert UNIX timestamp to datetime format
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
then you want to store this data to field value of RecyclerView
then you can format it from this time format like h:mm
I would like to change the font of my 'item' in recycleview with custom font. Anybody can help me with this? I manage to change the font for my header by using
header_title = (TextView) itemView.findViewById(R.id.header_title);
and
Typeface face_01 = Typeface.createFromAsset(itemView.getContext().getAssets(), "customfont/grb.otf");
header_title.setTypeface(face_01);
But i have no idea how to do that for item in arraylist.
Here is the java code for my adapter:-
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
private List<Item> data;
public ExpandableListAdapter(List<Item> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
Context context = parent.getContext();
float dp = context.getResources().getDisplayMetrics().density;
int subItemPaddingLeft = (int) (18 * dp);
int subItemPaddingTopAndBottom = (int) (5 * dp);
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_header, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
TextView itemTextView = new TextView(context);
itemTextView.setPadding(subItemPaddingLeft, subItemPaddingTopAndBottom, 0, subItemPaddingTopAndBottom);
itemTextView.setTextColor(0x88000000);
itemTextView.setLayoutParams(
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return new RecyclerView.ViewHolder(itemTextView) {
};
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.text);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = data.indexOf(itemController.refferalItem);
while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
} else {
int pos = data.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
TextView itemTextView = (TextView) holder.itemView;
itemTextView.setText(data.get(position).text);
break;
}
}
#Override
public int getItemViewType(int position) {
return data.get(position).type;
}
#Override
public int getItemCount() {
return data.size();
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
Typeface face_01 = Typeface.createFromAsset(itemView.getContext().getAssets(), "customfont/grb.otf");
header_title.setTypeface(face_01);
}
}
public static class Item {
public int type;
public String text;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
Gloabally define fontpath and typeface
Typeface typeface;
String fontpath = "fonts/KaushanScript-Regular.otf";
In your constructor do following
public ExpandableListAdapter(Context context,List<Item> data) {
typeface = Typeface.createFromAsset(context.getAssets(), fontpath);
this.data = data;
}
In your BindViewHolder
holder.itemTextView.setTypeface(typeface);
I get this error in the LogCat when I try to run the application.
java.lang.IllegalArgumentException: Context must not be null.
This happens when I add the Picasso code in the class.
here is the adpater.Java
It says the Context is null, I have read other posts but I could not find a solution.
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{
private List<App> mApps;
private boolean mHorizontal;
private boolean mPager;
private Context mContext;
public Adapter(Context ctx, boolean horizontal, boolean pager, List<App> apps) {
mHorizontal = horizontal;
mApps = apps;
mPager = pager;
this.mContext=ctx;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (mPager) {
return new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.adaper_pager, parent, false));
} else {
return mHorizontal ? new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter, parent, false)) :
new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_vertical, parent, false));
}
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
App app = mApps.get(position);
//holder.imageView.setImageResource(app.getDrawable());
Picasso.with(mContext).load(app.getLink()).into(holder.imageView);
holder.nameTextView.setText(app.getName());
holder.ratingTextView.setText(String.valueOf(app.getRating()));
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public int getItemCount() {
return mApps.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public TextView nameTextView;
public TextView ratingTextView;
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.igOne);
nameTextView = (TextView) itemView.findViewById(R.id.nameTV);
ratingTextView = (TextView) itemView.findViewById(R.id.rate);
}
}
}
Please Help. some say it is because the imageView is null. I have no idea about that.
MainActivity
public class MainActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {
private static final String TAG = "MainActivity";
private Context mContext = MainActivity.this;
private static final int ACTIVITY_NUM = 0;
public static final String ORIENTATION = "orientation";
private RecyclerView mRecyclerView;
private boolean mHorizontal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "OnCreate: Starting MainActivity");
setupBottomNavigationView();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
if (savedInstanceState == null) {
mHorizontal = true;
} else {
mHorizontal = savedInstanceState.getBoolean(ORIENTATION);
}
setupAdapter();
}
/**
* Setup Bottom Navigation View
*/
private void setupBottomNavigationView() {
Log.d(TAG, "setupBottomNavigationView: Setting up Bottom Navigation View");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottom_nav_bar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(mContext, bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
public void click(View v) {
Intent mIntent = null;
switch (v.getId()) {
case R.id.serve:
mIntent = new Intent(this, SearchActivity.class);
break;
case R.id.imageButton2:
mIntent = new Intent(this, SearchActivity.class);
break;
}
startActivity(mIntent);
}
///////////
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(ORIENTATION, mHorizontal);
}
private void setupAdapter() {
List<App> apps = getApps();
SnapAdapter snapAdapter = new SnapAdapter();
if (mHorizontal) {
snapAdapter.addSnap(new Snap(Gravity.CENTER_HORIZONTAL, "Snap Start", apps));
snapAdapter.addSnap(new Snap(Gravity.START, "Snap Middle", apps));
snapAdapter.addSnap(new Snap(Gravity.END, "Snap End", apps));
snapAdapter.addSnap(new Snap(Gravity.CENTER, "Pager snap", apps));
} else {
snapAdapter.addSnap(new Snap(Gravity.CENTER_VERTICAL, "Snap center", apps));
snapAdapter.addSnap(new Snap(Gravity.TOP, "Snap top", apps));
snapAdapter.addSnap(new Snap(Gravity.BOTTOM, "Snap bottom", apps));
}
mRecyclerView.setAdapter(snapAdapter);
}
private List<App> getApps() {
List<App> apps = new ArrayList<>();
apps.add(new App("Google+", "http://uupload.ir/files/aud7_brickone.jpg", 4.6f));
return apps;
}
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
}
SnapAdapter
public class SnapAdapter extends RecyclerView.Adapter<SnapAdapter.ViewHolder> implements GravitySnapHelper.SnapListener {
public static final int VERTICAL = 0;
public static final int HORIZONTAL = 1;
private Context mContext;
private ArrayList<Snap> mSnaps;
// Disable touch detection for parent recyclerView if we use vertical nested recyclerViews
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
};
public SnapAdapter() {
mSnaps = new ArrayList<>();
}
public void addSnap(Snap snap) {
mSnaps.add(snap);
}
#Override
public int getItemViewType(int position) {
Snap snap = mSnaps.get(position);
switch (snap.getGravity()) {
case Gravity.CENTER_VERTICAL:
return VERTICAL;
case Gravity.CENTER_HORIZONTAL:
return HORIZONTAL;
case Gravity.START:
return HORIZONTAL;
case Gravity.TOP:
return VERTICAL;
case Gravity.END:
return HORIZONTAL;
case Gravity.BOTTOM:
return VERTICAL;
}
return HORIZONTAL;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = viewType == VERTICAL ? LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_snap_vertical, parent, false)
: LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_snap, parent, false);
if (viewType == VERTICAL) {
view.findViewById(R.id.recycle_view).setOnTouchListener(mTouchListener);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Snap snap = mSnaps.get(position);
holder.snapTextView.setText(snap.getText());
if (snap.getGravity() == Gravity.START || snap.getGravity() == Gravity.END) {
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder
.recyclerView.getContext(), LinearLayoutManager.HORIZONTAL, false));
holder.recyclerView.setOnFlingListener(null);
new GravitySnapHelper(snap.getGravity(), false, this).attachToRecyclerView(holder.recyclerView);
} else if (snap.getGravity() == Gravity.CENTER_HORIZONTAL) {
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder
.recyclerView.getContext(), snap.getGravity() == Gravity.CENTER_HORIZONTAL ?
LinearLayoutManager.HORIZONTAL : LinearLayoutManager.VERTICAL, false));
holder.recyclerView.setOnFlingListener(null);
new LinearSnapHelper().attachToRecyclerView(holder.recyclerView);
} else if (snap.getGravity() == Gravity.CENTER) { // Pager snap
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder
.recyclerView.getContext(), LinearLayoutManager.HORIZONTAL, false));
holder.recyclerView.setOnFlingListener(null);
new PagerSnapHelper().attachToRecyclerView(holder.recyclerView);
} else { // Top / Bottom
holder.recyclerView.setLayoutManager(new LinearLayoutManager(holder
.recyclerView.getContext()));
holder.recyclerView.setOnFlingListener(null);
new GravitySnapHelper(snap.getGravity()).attachToRecyclerView(holder.recyclerView);
}
holder.recyclerView.setAdapter(new Adapter(mContext, snap.getGravity() == Gravity.START
|| snap.getGravity() == Gravity.END
|| snap.getGravity() == Gravity.CENTER_HORIZONTAL,
snap.getGravity() == Gravity.CENTER, snap.getApps()));
}
#Override
public int getItemCount() {
return mSnaps.size();
}
#Override
public void onSnap(int position) {
Log.d("Snapped: ", position + "");
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView snapTextView;
public RecyclerView recyclerView;
public ViewHolder(View itemView) {
super(itemView);
snapTextView = (TextView) itemView.findViewById(R.id.snapTextView);
recyclerView = (RecyclerView) itemView.findViewById(R.id.recycle_view);
}
}
}
java.lang.IllegalArgumentException: Context must not be null.
A constructor in Java is a block of code similar to a method that's
called when an instance of an object is created.
You should pass Context
private Context mContext;
public Adapter(Context ctx,boolean horizontal, boolean pager, List<App> apps) {
mHorizontal = horizontal;
mApps = apps;
mPager = pager;
this.mContext=ctx; // Call here
}
Logcat Throws
the error is: Error:(110, 40) error: constructor Adapter in class
Adapter cannot be applied to given types; required:
boolean,boolean,List,Context found: boolean,boolean,List
reason: actual and formal argument lists differ in length
Pass Value LIKE
new Adapter(Your_Activity.this, boolean, boolean , List<App>);
Call Adapter like this
Adapter mAdapter = new Adapter (Youractivity_name.this, boolean, boolean , list);
and change the constructor to
public Adapter(Context context ,boolean horizontal, boolean pager, List<App> apps) {
mHorizontal = horizontal;
mApps = apps;
mPager = pager;
mContext = context;
}