In my application I get some data from server and show this into my recyclerView.
I want show all of list content not show just item 0.
My adapter codes:
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.ViewHolder> {
private ArrayList<Post> postList;
private Context context;
private ListItemClickListener itemClickListener;
public PostsAdapter(Context context, ArrayList<Post> allPostList) {
this.context = context;
postList = allPostList;
}
public void setItemClickListener(ListItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post, parent, false);
return new ViewHolder(view, viewType, itemClickListener);
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imgPost;
private TextView tvPostTitle, tvPostCategory, tvPostDate;
private CardView mCardView;
private ListItemClickListener itemClickListener;
public ViewHolder(View itemView, int viewType, ListItemClickListener itemClickListener) {
super(itemView);
this.itemClickListener = itemClickListener;
// Find all views ids
imgPost = (ImageView) itemView.findViewById(R.id.post_img);
tvPostTitle = (TextView) itemView.findViewById(R.id.title_text);
tvPostCategory = (TextView) itemView.findViewById(R.id.post_category);
tvPostDate = (TextView) itemView.findViewById(R.id.date_text);
mCardView = (CardView) itemView.findViewById(R.id.card_view_top);
mCardView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (itemClickListener != null) {
itemClickListener.onItemClick(getLayoutPosition(), view);
}
}
}
#Override
public int getItemCount() {
return (null != postList ? postList.size() : 0);
}
#Override
public void onBindViewHolder(PostsAdapter.ViewHolder mainHolder, int position) {
final Post model = postList.get(position);
// setting data over views
String title = model.getTitle().getRendered();
mainHolder.tvPostTitle.setText(Html.fromHtml(title));
String imgUrl = null;
if (model.getEmbedded().getWpFeaturedMedias().size() > 0) {
if (model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails() != null) {
if (model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl() != null) {
imgUrl = model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl();
}
}
}
if (imgUrl != null) {
Glide.with(context)
.load(imgUrl)
.into(mainHolder.imgPost);
} else {
Glide.with(context)
.load(R.color.imgPlaceholder)
.into(mainHolder.imgPost);
}
String category = null;
if (model.getEmbedded().getWpTerms().size() >= 1) {
category = model.getEmbedded().getWpTerms().get(0).get(0).getName();
}
if (category == null) {
category = context.getResources().getString(R.string.default_str);
}
mainHolder.tvPostCategory.setText(Html.fromHtml(category));
mainHolder.tvPostDate.setText(model.getFormattedDate());
}
}
but in above code just show me item 0 , but I want show all of items.
how can I it?
Try this
for (int i = 0; i < model.getEmbedded().getWpTerms().size(); i++) {
for (int j=0;j<model.getEmbedded().getWpTerms().get(i).size();j++){
Log.e("DATA",model.getEmbedded().getWpTerms().get(i).get(j).getName());
}
}
String category = "";
for(int i=0; response.size();i++){
{
category = category + "," + model.getEmbedded().getWpTerms().get(i).get(i).getName();
}
If you have used recyclerview , its adapter has onBindViewHolder() method , which gives you a position variable. Use that to iterate through the list!
model.getEmbedded().getWpFeaturedMedias().get(position).getMediaDetails()
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.
I have a fragment containing a recyclerView.
When a user presses on one of their recorded exercise sets, the particular set is highlighted green.
Basically this allows them to update the weight/ reps for that particular set if they want to.
When a user then decides to press the update button, I will run a SQL query to update the weight/ reps as they entered, however I also need to deselect the selected set (recyclerView item).
I need the colour to return back to dark grey. How could this be achieved?
Fragment (Relative Code)
#Override
public void onExerciseClicked(int position) {
if (recyclerItemClicked == false) {
saveBtn.setText("Update");
clearBtn.setVisibility(View.GONE);
recyclerItemClicked = true;
double selectedWeight = adapter.getWeight(position);
String selectedWeightString = Double.toString(selectedWeight);
editTextWeight.setText(selectedWeightString);
int selectedReps = adapter.getReps(position);
String selectedRepsString = Integer.toString(selectedReps);
editTextReps.setText(selectedRepsString);
} else {
clearBtn.setVisibility(View.VISIBLE);
saveBtn.setText("Save");
recyclerItemClicked = false;
}
}
public void initRecyclerView() {
adapter = new CompletedExercisesListAdapter2(allExercises, this);
recyclerView.setAdapter(adapter);
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
}
Adapter
public class CompletedExercisesListAdapter2 extends RecyclerView.Adapter {
private OnExerciseClickListener onExerciseClickListener;
private List<Log_Entries> allCompletedExercises = new ArrayList<>();
public int adapterPos = -1;
public boolean isSelected = false;
public boolean swipeDetected = false;
public CompletedExercisesListAdapter2(ArrayList<Log_Entries> allCompletedExercises, OnExerciseClickListener onExerciseClickListener) {
this.allCompletedExercises = allCompletedExercises;
this.onExerciseClickListener = onExerciseClickListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view;
if (viewType == 0) {
view = layoutInflater.inflate(R.layout.new_completed_exercise_item, parent, false);
return new ViewHolderOne(view, onExerciseClickListener);
}
view = layoutInflater.inflate(R.layout.completed_exercise_item, parent, false);
return new ViewHolderTwo(view, onExerciseClickListener);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == 0) {
ViewHolderOne viewHolderOne = (ViewHolderOne) holder;
Log.d("adapterPos", String.valueOf(adapterPos));
Log.d("position", String.valueOf(position));
if (adapterPos == position) {
viewHolderOne.relativeLayout.setBackgroundColor(Color.parseColor("#567845"));
} else {
viewHolderOne.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
viewHolderOne.textViewExerciseName.setText(String.valueOf(allCompletedExercises.get(position).getChildExerciseName()));
viewHolderOne.textViewSetNumber.setText(String.valueOf(viewHolderOne.getAdapterPosition() + 1));
viewHolderOne.textViewWeight.setText(String.valueOf(allCompletedExercises.get(position).getTotal_weight_lifted()));
viewHolderOne.textViewReps.setText(String.valueOf(allCompletedExercises.get(position).getReps()));
} else if (getItemViewType(position) == 1) {
ViewHolderTwo viewHolderTwo = (ViewHolderTwo) holder;
if (adapterPos == position) {
viewHolderTwo.relativeLayout.setBackgroundColor(Color.parseColor("#567845"));
} else {
viewHolderTwo.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
if(adapterPos >-1 && swipeDetected == true){
viewHolderTwo.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
viewHolderTwo.textViewSetNumber.setText(String.valueOf(viewHolderTwo.getAdapterPosition() + 1));
viewHolderTwo.textViewWeight.setText(String.valueOf(allCompletedExercises.get(position).getTotal_weight_lifted()));
viewHolderTwo.textViewReps.setText(String.valueOf(allCompletedExercises.get(position).getReps()));
}
}
#Override
public int getItemCount() {
return allCompletedExercises.size();
}
#Override
public int getItemViewType(int position) {
// if list is sorted chronologically
if (position == 0) {
return 0;
}
if (allCompletedExercises.get(position).getChildExerciseName().equals(allCompletedExercises.get(position - 1).getChildExerciseName())) {
return 1;
} else {
return 0;
}
}
public class ViewHolderOne extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewExerciseName;
private TextView textViewSetNumber;
private TextView textViewWeight;
private TextView textViewReps;
OnExerciseClickListener mOnExerciseClickListener;
private RelativeLayout relativeLayout;
public ViewHolderOne(#NonNull View itemView, OnExerciseClickListener onExerciseClickListener) {
super(itemView);
textViewExerciseName = itemView.findViewById(R.id.textView_ExerciseName3);
textViewSetNumber = itemView.findViewById(R.id.textView_Set_Number56);
textViewWeight = itemView.findViewById(R.id.textView_weight78);
textViewReps = itemView.findViewById(R.id.textView_repss0);
mOnExerciseClickListener = onExerciseClickListener;
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.exercise_item_relative);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExerciseClickListener.onExerciseClicked(getAdapterPosition());
if (isSelected) {
adapterPos = -1;
isSelected = false;
} else {
adapterPos = getAdapterPosition();
isSelected = true;
}
notifyDataSetChanged();
}
}
class ViewHolderTwo extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewSetNumber;
private TextView textViewWeight;
private TextView textViewReps;
OnExerciseClickListener mOnExerciseClickListener;
private RelativeLayout relativeLayout;
public ViewHolderTwo(#NonNull View itemView, OnExerciseClickListener onExerciseClickListener) {
super(itemView);
textViewSetNumber = itemView.findViewById(R.id.textView_Set_Number);
textViewWeight = itemView.findViewById(R.id.textView_weight);
textViewReps = itemView.findViewById(R.id.textView_repss);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.exercise_item_rel);
mOnExerciseClickListener = onExerciseClickListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExerciseClickListener.onExerciseClicked(getAdapterPosition());
if (!isSelected) {
adapterPos = getAdapterPosition();
isSelected = true;
} else {
adapterPos = -1;
isSelected = false;
}
notifyDataSetChanged();
}
}
public interface OnExerciseClickListener {
void onExerciseClicked(int position);
}
}
}
Create a separate method in your adapter for clearing the selection.
public void clearSelection() {
adapterPos = -1;
isSelected = false;
notifyDataSetChanged();
}
Then call adapter.clearSelection() from your update click listener.
I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}
I have RecycleView List with an ExpandableLinearLayout ( i use a third party library). In my ExpandableLinearLayout I have a ListView, with an custom ArrayAdapter.
I set my Adapter in the RecycleViewAdapter and submit one ArrayList that contains 4 ArrayLists and the position from the onBindViewHolder() method , too fill the different sections in the RecycleView.
I pass the data in the correct section but i get only the first element of each ArrayList. I Log some stuff and the problem is the position from the getView method in my ArrayAdapter is always 0..
I search and played around a bit but i didnt found a solution.. I hope somebody can help..
Sorry for my bad grammar
This is my RecycleView :
public class EmergencyPassAdapter extends RecyclerView.Adapter<EmergencyPassAdapter.EmergencyPassViewHolder> {
private static final String LOG_TAG = EmergencyPassAdapter.class.getName();
private Context context;
private ArrayList<CellInformation> cellInformations;
private SparseBooleanArray expandState = new SparseBooleanArray();
EmergencyPassExpandAdapter emergencyPassExpandAdapter;
public EmergencyPassAdapter(Context context, ArrayList<CellInformation> cellInformations) {
this.context = context;
this.cellInformations = cellInformations;
for (int i = 0; i < cellInformations.size(); i++) {
expandState.append(i, false);
}
}
#Override
public EmergencyPassViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_emergency_pass, parent, false);
return new EmergencyPassViewHolder(view);
}
#Override
public void onBindViewHolder(final EmergencyPassViewHolder holder, final int position) {
CellInformation cellInformation = cellInformations.get(position);
holder.imageViewIcon.setImageDrawable(cellInformation.getIcon());
holder.textViewTitle.setText(cellInformation.getTitel());
emergencyPassExpandAdapter = new EmergencyPassExpandAdapter(context, EmergencyPassExpandDetailFactory.getExpandCellInformation(context), position);
holder.listView.setAdapter(emergencyPassExpandAdapter);
if (cellInformation.getTitel().equals(context.getResources().getString(R.string.emergency_informations_health_insurance_emergency_contacts))) {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
} else if (cellInformation.getTitel().equals(context.getResources().getString(R.string.emergency_informations_health_insurance_legal_guardian))) {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
} else {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
}
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!holder.expandableLinearLayout.isExpanded()) {
Log.i(LOG_TAG, "expand");
holder.expandableLinearLayout.expand();
} else {
Log.i(LOG_TAG, "collapse");
holder.expandableLinearLayout.collapse();
}
}
});
}
#Override
public int getItemCount() {
return cellInformations.size();
}
public static class EmergencyPassViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle, textViewExpandText;
ImageView imageViewIcon, imageViewArrow;
ExpandableLinearLayout expandableLinearLayout;
RelativeLayout relativeLayout;
ListView listView;
public EmergencyPassViewHolder(View itemView) {
super(itemView);
textViewTitle = (TextView) itemView.findViewById(R.id.cell_emergency_pass_title_tv);
textViewExpandText = (TextView) itemView.findViewById(R.id.cell_emergency_pass_expand_detail_tv);
imageViewIcon = (ImageView) itemView.findViewById(R.id.cell_emergency_pass_icon_iv);
imageViewArrow = (ImageView) itemView.findViewById(R.id.cell_emergency_pass_arrow_icon_iv);
expandableLinearLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.cell_emergency_pass_arrow_expandable_list);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.cell_emergency_pass_root_rl);
listView = (ListView) itemView.findViewById(R.id.cell_emergency_pass_expand_lv);
}
}
}
My ArrayAdapter
public class EmergencyPassExpandAdapter extends ArrayAdapter<CellExpandInformation>{
private static final String LOG_TAG = EmergencyPassExpandAdapter.class.getName();
private ArrayList<CellExpandInformation> values;
private int checkPosition;
private Context context;
public EmergencyPassExpandAdapter(Context context, ArrayList<CellExpandInformation> values, int checkPosition) {
super(context, -1, values);
this.context = context;
this.values = values;
this.checkPosition = checkPosition;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i(LOG_TAG,"View");
Log.i(LOG_TAG,"Position: " + position);
EmergencyPassExpandViewHolder viewHolder;
CellExpandInformation cellExpandInformation = values.get(position);
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.cell_emergency_pass_expand, parent, false);
viewHolder = new EmergencyPassExpandViewHolder();
viewHolder.textViewExpandTitle = (TextView) convertView.findViewById(R.id.cell_emergency_pass_expand_detail_tv);
convertView.setTag(viewHolder);
} else {
viewHolder = (EmergencyPassExpandViewHolder) convertView.getTag();
}
Log.i(LOG_TAG,"CheckPosition: " + checkPosition);
if (values != null) {
if (checkPosition == 0) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getMedications().get(position).getMedicationName());
Log.i(LOG_TAG, "Medications: " + cellExpandInformation.getMedications().get(position).getMedicationName());
} else if (checkPosition == 1) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getAllergies().get(position).getAllgergiesName());
} else if (checkPosition == 2) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getDiseases().get(position).getDiseasesName());
} else if (checkPosition == 3) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getLegalGuradian().get(position).getGuradianName());
} else if (checkPosition == 4) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getEmergencyContact().get(position).getEmergencyContactName());
}
}
for(int i = 0; i < cellExpandInformation.getMedications().size(); i++){
Log.i(LOG_TAG,"Medis: " + cellExpandInformation.getMedications().get(i).getMedicationName());
}
return convertView;
}
static class EmergencyPassExpandViewHolder {
TextView textViewExpandTitle;
ImageView imageViewPhone, imageViewEmail, imageViewAdd;
}
}
I want to mark radio button true in listview onItemClick so what I am doing is
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
LinearLayout item_view = (LinearLayout) view;
final RadioButton itemcheck = (RadioButton) item_view
.findViewById(R.id.listview_radiobutton);
if (itemcheck.isChecked()) {
itemcheck.setChecked(true);
} else {
itemcheck.setChecked(false);
}
itemcheck.setChecked(true);
}
My listview
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginLeft="#dimen/view_margin_15"
android:layout_marginRight="#dimen/view_margin_15"
android:layout_marginTop="#dimen/view_margin_20"
android:layout_weight="1"
android:choiceMode="singleChoice"
android:divider="#drawable/list_divider"
android:dividerHeight="#dimen/padding_2"
android:fastScrollEnabled="true"
android:footerDividersEnabled="true"
android:listSelector="#null"
android:scrollbars="none"
android:textFilterEnabled="true"
android:textStyle="normal" />
Edit:--
My Adapter code :--
public class Adapter extends ArrayAdapter<Details> {
private Context mContext;
private List<Details> transList;
private LayoutInflater infalInflater;
private OnCheckedRadioButon onCheckedRadioButon;
private Typeface mTypeface, mEditTypeface, mPasswdTypeface;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private PromoViewHolder viewHolder;
public Adapter(Context context, List<Details> mtransList, OnCheckedRadioButon onCheckedRadioButon) {
super(context, R.layout.dialog_listview, mtransList);
this.mContext = context;
this.transList = mtransList;
this.onCheckedRadioButon = onCheckedRadioButon;
this.infalInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
try {
viewHolder = null;
row = infalInflater.inflate(R.layout.dialog_listview_code, parent, false);
viewHolder = new ViewHolder();
viewHolder.radiobutton = (RadioButton) row.findViewById(R.id.radiobutton);
viewHolder.listview_name = (TextView) row.findViewById(R.id.listview_name);
setValueText(viewHolder, position);
viewHolder.radiobutton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
onCheckedRadioButon.onCheckedButton(transList.get(position));
}
}
});
viewHolder.radiobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position != mSelectedPosition && mSelectedRB != null) {
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
mSelectedRB = (RadioButton) v;
}
});
if (mSelectedPosition != position) {
viewHolder.radiobutton.setChecked(false);
} else {
viewHolder.radiobutton.setChecked(true);
if (mSelectedRB != null && viewHolder.radiobutton != mSelectedRB) {
mSelectedRB = viewHolder.radiobutton;
}
}
row.setTag(viewHolder);
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
private void setValueText(ViewHolder viewHolder, final int position) {
viewHolder.listview_name.setText(transList.get(position).getName());
}
public interface OnCheckedRadioButon {
void onCheckedButton(Details pr);
}
class ViewHolder {
RadioButton radiobutton;
TextView listview_name;
}
}
It is working but if I click on another position of the listview then the previous radiobutton position is not unchecked.I want to uncheck all the previous ones and mark only one at a time.
Any help will be appreciated.
Use POJO classes (Setter or Getter) to manage this type of condition. Use boolean variable in that class and change its values according to the position true or false.
POJO Class Like :
public class CheckListSource {
public boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
In your adapter :
private ArrayList<CheckListSource > itemsData;
public ChildListAdapter(Activity activity, ArrayList<ChildListResponse> baseResponse) {
this.itemsData = baseResponse;
this.activity = activity;
}
In BindViewHolder Like :
viewHolder.checkParentView.setTag(itemsData.get(position));
viewHolder.checkParentView.setOnClickListener(checkedListener);
private View.OnClickListener checkedListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckListSource childListResponse = (CheckListSource ) v.getTag();
if (childListResponse.isSelected())
childListResponse.setSelected(false);
else
childListResponse.setSelected(true);
notifyDataSetChanged();
}
};
Use a boolean array in your Activity. Each boolean value corresponds to a RadioButton.
If a RadioButton is checked, set its boolean value to true, and set all other boolean values in the array to false.
In the getView() of your Adapter, call your_radio_button.setChecked(your_boolean_array[position]).
Once the boolean array is modified, call your_adapter.notifyDataSetChanged().
Checkout this it works for me..
public class ProgramAdapter extends ArrayAdapter<KeyInformation> {
private final String TAG = "ProgramAdapter";
private List<KeyInformation> mList;
private Context mContext;
private LayoutInflater mInflater;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private String mUserApllication = "";
public ProgramAdapter(Context context, List<KeyInformation> objects) {
super(context, R.layout.program_item, objects);
mContext = context;
mList = objects;
mInflater = ( LayoutInflater ) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mUserApllication = Settings.System.getString(mContext.getContentResolver(),
Settings.System.PROGRAMMABLE_KEY_ACTION);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.program_item, parent, false);
holder.mImageView = (ImageView) convertView.findViewById(R.id.icon);
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
holder.mSeparator = (TextView) convertView.findViewById(R.id.title_separator);
holder.mRadioButton = (RadioButton) convertView.findViewById(R.id.radioBtn);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mRadioButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
if(position != mSelectedPosition && mSelectedRB != null){
mSelectedRB.setChecked(false);
}
mUserApllication ="";
mSelectedPosition = position;
mSelectedRB = (RadioButton) view;
}
});
String userApp = mList.get(position).packageName;
if(mUserApllication.equals(userApp)) {
mSelectedPosition = position;
}
if (mSelectedPosition != position) {
holder.mRadioButton.setChecked(false);
} else {
holder.mRadioButton.setChecked(true);
mSelectedRB = holder.mRadioButton;
}
holder.mImageView.setImageDrawable(mList.get(position).icon);
holder.mTextView.setText(mList.get(position).lable);
if (position == 5) {
holder.mSeparator.setVisibility(View.VISIBLE);
} else {
holder.mSeparator.setVisibility(View.GONE);
}
return convertView;
}
public int getmSelectedPosition () {
return mSelectedPosition;
}
private static class ViewHolder {
ImageView mImageView;
TextView mTextView;
TextView mSeparator;
RadioButton mRadioButton;
}
}
Please go through below, it will work.
class Details{
public boolean isSelect=false;
}
public class Adapter extends ArrayAdapter<Details> {
private Context mContext;
private List<Details> transList;
private LayoutInflater infalInflater;
private OnCheckedRadioButon onCheckedRadioButon;
private Typeface mTypeface, mEditTypeface, mPasswdTypeface;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private PromoViewHolder viewHolder;
public Adapter(Context context, List<Details> mtransList, OnCheckedRadioButon onCheckedRadioButon) {
super(context, R.layout.dialog_listview, mtransList);
this.mContext = context;
this.transList = mtransList;
this.onCheckedRadioButon = onCheckedRadioButon;
this.infalInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void updateList(){
viewHolder.radiobutton.setChecked(false);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
try {
viewHolder = null;
row = infalInflater.inflate(R.layout.dialog_listview_code, parent, false);
viewHolder = new ViewHolder();
viewHolder.radiobutton = (RadioButton) row.findViewById(R.id.radiobutton);
viewHolder.listview_name = (TextView) row.findViewById(R.id.listview_name);
setValueText(viewHolder, position);
viewHolder.radiobutton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
onCheckedRadioButon.onCheckedButton(transList.get(position));
}
}
});
viewHolder.radiobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Details detail=transList.get(position);
for(int i=0;i<transList.size;i++){
Detail b=transList.get(i);
b.isSelect=false;
}
detail.isSelect=true;
adapter.notifydatasetchange();
}
});
Details detail=transList.get(position);
if (detail.isSelect) {
viewHolder.radiobutton.setChecked(true);
} else {
viewHolder.radiobutton.setChecked(false);
}
row.setTag(viewHolder);
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
private void setValueText(ViewHolder viewHolder, final int position) {
viewHolder.listview_name.setText(transList.get(position).getName());
}
public interface OnCheckedRadioButon {
void onCheckedButton(PromoDetails promoDetails);
}
class ViewHolder {
RadioButton radiobutton;
TextView listview_name;
}
}