How can I change the colour of recyclerView item on button pressed? - java

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.

Related

Android survey app with multiple viewholders and viewpager

in my app I'm creating a survey with multiple question types like radio button, checkboxes, dropdown, photo, stars, textbox. Survey has a number of pages and for this case I'm using a viewpager.
Radio buttons and checkboxes are generated dynamically, questions can have a comment field and some them can have optional fields.
In each page I have a recyclerview where I display types of questions. The problem is when I want to save the data, it is not working. Now I have an adapter for ViewPager and another one for recyclerview. In each view holder of recyclerview I have to save the data to Sqlite database when I click finish button in the viewpager. I'm trying to use an interface to communicate but the data are not saved correctly.
Here what I have on my viewpager adapter:
public class SurveyPagerAdapter extends PagerAdapter {
private final List<RecyclerView> mViews;
private final List<Page> mPages;
private final Context mContext;
private final AppCompatActivity mActivity;
private final ViewPager viewPager;
// ArrayList<SurveyListLines> surveyLinesList;
ArrayList<Integer> requiredQuestions;
private final Location location;
private final MutableLiveData<Integer> liveData = new MutableLiveData<>();
SettingsManager manager;
String code;
int headerId;
private final onSaveCallback onSaveCallback;
private final boolean hasAnswers;
private List<Answers> answersList;
private final String clientCode;
int questionId;
private static OnButtonSendPressedCallback mButtonSendPressedCallback;
public static void setOnButtonSendPressedCallback(OnButtonSendPressedCallback onButtonSendPressedCallback) {
mButtonSendPressedCallback = onButtonSendPressedCallback;
}
public SurveyPagerAdapter(List<RecyclerView> views, List<Page> pages, Context context,
AppCompatActivity activity, ViewPager viewPager, Location location,
onSaveCallback onSaveCallback, boolean hasAnswers, String clientCode) {
mViews = views;
mPages = pages;
mContext = context;
mActivity = activity;
this.viewPager = viewPager;
requiredQuestions = new ArrayList<>();
manager = SettingsManager.getInstance(mContext);
this.location = location;
this.onSaveCallback = onSaveCallback;
this.hasAnswers = hasAnswers;
this.clientCode = clientCode;
}
public List<Answers> getAnswersList() {
return answersList;
}
public void setAnswersList(List<Answers> answersList) {
this.answersList = answersList;
}
private String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public View getView(int position) {
return mViews.get(position);
}
#Override
public int getCount() {
return mPages.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
final ConstraintLayout view = (ConstraintLayout) LayoutInflater.from(container.getContext()).inflate(R.layout.survey_container, container, false);
final RecyclerView recyclerView = view.findViewById(R.id.my_recycler_view);
final Button buttonNext = view.findViewById(R.id.button_next);
final Button buttonPrev = view.findViewById(R.id.button_prev);
for (Questions question : mPages.get(position).getQuestions()) {
if (question.isRequired()) {
requiredQuestions.add(question.getId());
}
}
buttonPrev.setVisibility(View.GONE);
SurveyPagerListAdapter detailsAdapter = new SurveyPagerListAdapter(mContext, mActivity,
mPages.get(position).getQuestions(), hasAnswers, getAnswersList(),
clientCode);
// Create recycler view for each page
recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
recyclerView.setAdapter(detailsAdapter);
recyclerView.setNestedScrollingEnabled(true);
// Manage previous and next buttons
liveData.observe(mActivity, index -> {
if (!hasAnswers) {
if (mPages.size() > 1) {
if (position == 0) {
buttonPrev.setVisibility(View.GONE);
buttonNext.setText(mContext.getString(R.string.next_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_baseline_arrow_forward_ios_24, 0);
} else if (position == getCount() - 1) {
buttonPrev.setVisibility(View.GONE);
buttonNext.setText(mContext.getString(R.string.send_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
} else {
buttonPrev.setVisibility(View.VISIBLE);
buttonNext.setText(mContext.getString(R.string.next_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_baseline_arrow_forward_ios_24, 0);
}
} else if (mPages.size() == 1) {
buttonPrev.setVisibility(View.GONE);
buttonNext.setText(mContext.getString(R.string.send_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
} else {
buttonPrev.setVisibility(View.GONE);
}
} else {
if (mPages.size() > 0) {
if (position == 0) {
if (mPages.size() == 1) {
buttonPrev.setVisibility(View.GONE);
buttonNext.setVisibility(View.GONE);
} else {
buttonPrev.setVisibility(View.GONE);
buttonNext.setText(mContext.getString(R.string.next_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_baseline_arrow_forward_ios_24, 0);
}
} else if (position == getCount() - 1) {
buttonPrev.setVisibility(View.VISIBLE);
buttonNext.setVisibility(View.GONE);
} else {
buttonPrev.setVisibility(View.VISIBLE);
buttonNext.setText(mContext.getString(R.string.next_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_baseline_arrow_forward_ios_24, 0);
}
}
}
});
final ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
liveData.postValue(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
viewPager.setOnPageChangeListener(onPageChangeListener);
onPageChangeListener.onPageSelected(viewPager.getCurrentItem());
buttonNext.setOnClickListener(onNextClickListener);
buttonPrev.setOnClickListener(onBackClickListener);
container.addView(view);
headerId = mPages.get(position).getHeaderId();
return view;
}
private void processSendingSurvey() {
SurveyListHeader surveyListHeaderDb = new SurveyListHeader();
Date currentDate = new Date();
String closedDate = new SimpleDateFormat(SoapApi.SEND_DATE_FORMAT_Z, Locale.getDefault()).format(currentDate);
ArrayList<SurveyListHeader> surveyListDB = SurveyListHeader.selectAllSingle(Utils.getDb(mContext));
for (SurveyListHeader header : surveyListDB) {
if (header.getCode().equals(getCode())) {
surveyListHeaderDb.setCode(getCode());
surveyListHeaderDb.setCustomerCode(header.getCustomerCode());
surveyListHeaderDb.setCustomerType(header.getCustomerType());
surveyListHeaderDb.setOpenDate(header.getOpenDate());
surveyListHeaderDb.setOpenLatitude(header.getOpenLatitude());
surveyListHeaderDb.setOpenLongitude(header.getOpenLongitude());
surveyListHeaderDb.setClosedDate(closedDate);
surveyListHeaderDb.setClosedLatitude(String.valueOf(location.getLongitude()));
surveyListHeaderDb.setClosedLongitude(String.valueOf(location.getLatitude()));
ArrayList<SurveyListLines> surveyLinesList = SurveyListLines.selectAll(Utils.getDb(mContext), questionId);
surveyListHeaderDb.setSurveyLines(surveyLinesList);
// if (surveyLinesList.size() > 0) {
ArrayList<SurveyListHeader> newList = new ArrayList<>();
newList.add(surveyListHeaderDb);
if (!Utils.isNetworkConnected(mContext)) {
if (closedDate.equals("-1")) {
surveyListHeaderDb.save(Utils.getDb(mContext));
}
} else {
sendRequest(newList);
}
// } else {
// Toast.makeText(mContext, mContext.getString(R.string.no_question_answered), Toast.LENGTH_SHORT).show();
// }
}
}
}
private void sendRequest(ArrayList<SurveyListHeader> surveyList) {
SurveyRequestAnswers requestAnswers = new SurveyRequestAnswers();
String userId = manager.getUserID();
String catalog = manager.getCatalog();
String username = manager.getUsername();
String userDescription = manager.getUserDesc();
String deviceId = manager.getDeviceId();
String lang = manager.getLanguage();
String versionNo = Utils.getVersionNo(mContext);
al.logic.android.webflex.survey.models.answers.UserData userData = new al.logic.android.webflex.survey.models.answers.UserData();
userData.setCatalog(catalog);
userData.setUserId(userId);
userData.setUserDescription(userDescription);
userData.setDeviceId(deviceId);
userData.setLang(lang);
userData.setUserName(username);
userData.setVersionNo(versionNo);
requestAnswers.setUserData(userData);
requestAnswers.setSurveyHeader(surveyList);
onSaveCallback.onSave(requestAnswers);
}
private final View.OnClickListener onNextClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!hasAnswers && viewPager.getCurrentItem() == getCount() - 1) {
mButtonSendPressedCallback.isPressed(true);
processSendingSurvey();
} else {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
mButtonSendPressedCallback.isPressed(true);
}
}
};
private final View.OnClickListener onBackClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1, true);
}
};
public List<RecyclerView> getViews() {
return mViews;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mPages.get(position).getDescription();
}
public interface onSaveCallback {
void onSave(SurveyRequestAnswers requestAnswers);
}
public interface OnButtonSendPressedCallback {
void isPressed(boolean isPressed);
}
}
And them my adapter is:
public class SurveyPagerListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final List<Questions> questions;
private final Context mContext;
private final AppCompatActivity mActivity;
private final boolean hasAnswers;
private final String clientCode;
private final List<Answers> answersList;
public SurveyPagerListAdapter(Context context, AppCompatActivity activity, List<Questions> questions,
boolean hasAnswers,
List<Answers> answersList, String clientCode) {
mContext = context;
mActivity = activity;
this.questions = questions;
this.hasAnswers = hasAnswers;
this.answersList = answersList;
this.clientCode = clientCode;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
if (viewType == R.layout.layout_survey_radio_buttons) {
view = inflater.inflate(R.layout.layout_survey_radio_buttons, parent, false);
return new RadioButtonsViewHolder(view, mContext, mActivity, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_checkboxes) {
view = inflater.inflate(R.layout.layout_survey_checkboxes, parent, false);
return new CheckboxesViewHolder(view, mContext, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_dropdown) {
view = inflater.inflate(R.layout.layout_survey_dropdown, parent, false);
return new SpinnerViewHolder(view, mContext, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_date) {
view = inflater.inflate(R.layout.layout_survey_date, parent, false);
return new DateViewHolder(view, mContext, mActivity, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_choose_file) {
view = inflater.inflate(R.layout.layout_survey_choose_file, parent, false);
return new ChoosePhotoViewHolder(view, mContext, mActivity, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_rating_stars) {
view = inflater.inflate(R.layout.layout_survey_rating_stars, parent, false);
return new RatingStarsViewHolder(view, mContext, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_rating_numbers) {
view = inflater.inflate(R.layout.layout_survey_rating_numbers, parent, false);
return new RatingNumberViewHolder(view, mContext, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_input) {
view = inflater.inflate(R.layout.layout_survey_input, parent, false);
return new EditTextViewHolder(view, mContext, hasAnswers, clientCode);
} else {
return null;
}
}
#Override
public int getItemViewType(int position) {
if (isRadioButton(position)) {
return R.layout.layout_survey_radio_buttons;
} else if (isCheckBox(position)) {
return R.layout.layout_survey_checkboxes;
} else if (isSpinner(position)) {
return R.layout.layout_survey_dropdown;
} else if (isDate(position)) {
return R.layout.layout_survey_date;
} else if (isChoosePhoto(position)) {
return R.layout.layout_survey_choose_file;
} else if (isRatingStars(position)) {
return R.layout.layout_survey_rating_stars;
} else if (isRatingNumbers(position)) {
return R.layout.layout_survey_rating_numbers;
} else if (isEditText(position)) {
return R.layout.layout_survey_input;
} else if (isString(position)) {
return R.layout.layout_survey_input;
} else {
return -1;
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
final Questions question = questions.get(position);
if (holder.getItemViewType() == R.layout.layout_survey_radio_buttons) {
if (holder instanceof RadioButtonsViewHolder) {
((RadioButtonsViewHolder) holder).bind(question);
((RadioButtonsViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_checkboxes) {
if (holder instanceof CheckboxesViewHolder) {
((CheckboxesViewHolder) holder).bind(question);
((CheckboxesViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_dropdown) {
if (holder instanceof SpinnerViewHolder) {
((SpinnerViewHolder) holder).bind(question);
((SpinnerViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_date) {
if (holder instanceof DateViewHolder) {
((DateViewHolder) holder).bind(question);
((DateViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_choose_file) {
if (holder instanceof ChoosePhotoViewHolder) {
((ChoosePhotoViewHolder) holder).bind(question);
((ChoosePhotoViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_rating_stars) {
if (holder instanceof RatingStarsViewHolder) {
((RatingStarsViewHolder) holder).bind(question);
((RatingStarsViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_rating_numbers) {
if (holder instanceof RatingNumberViewHolder) {
((RatingNumberViewHolder) holder).bind(question);
((RatingNumberViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_input) {
if (holder instanceof EditTextViewHolder) {
((EditTextViewHolder) holder).bind(question);
((EditTextViewHolder) holder).bindAnswers(answersList);
}
}
}
#Override
public int getItemCount() {
return questions == null ? 0 : questions.size();
}
private boolean isRadioButton(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_RADIO);
}
private boolean isCheckBox(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_CHECKBOX);
}
private boolean isSpinner(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_DROPDOWN);
}
private boolean isDate(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_DATE);
}
private boolean isChoosePhoto(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_IMAGE);
}
private boolean isRatingStars(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_STAR);
}
private boolean isRatingNumbers(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_NUMBER);
}
private boolean isEditText(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_TEXT_BOX);
}
private boolean isString(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_STRING);
}
}
and for example the Radio Button viewholder:
public class RadioButtonsViewHolder extends BaseViewHolder {
private final ImageView tooltipHelpButton;
private final TextView questionDescription;
private final TextInputLayout textViewComment;
private final RadioGroup radioGroup;
private final ImageView imageRequired;
private final TextInputEditText editTextComment;
private final EditText editTextOther;
private final Context mContext;
private final AppCompatActivity mActivity;
int questionId;
private final boolean hasAnswers;
private final String clientCode;
private int checkedRadioButtonId;
private int headerId;
public RadioButtonsViewHolder(#NonNull View itemView, Context context,
AppCompatActivity activity, boolean hasAnswers, String clientCode) {
super(itemView);
mContext = context;
mActivity = activity;
this.hasAnswers = hasAnswers;
this.clientCode = clientCode;
tooltipHelpButton = itemView.findViewById(R.id.tooltip_button);
questionDescription = itemView.findViewById(R.id.question_description);
radioGroup = itemView.findViewById(R.id.question_radio_group);
editTextOther = itemView.findViewById(R.id.question_radioButton_other);
imageRequired = itemView.findViewById(R.id.image_required);
textViewComment = itemView.findViewById(R.id.textView_question_comment);
editTextComment = itemView.findViewById(R.id.edittext_question_comment);
if (hasAnswers) {
editTextComment.setFocusable(false);
editTextComment.setEnabled(false);
editTextOther.setFocusable(false);
editTextOther.setEnabled(false);
tooltipHelpButton.setVisibility(View.GONE);
}
}
#Override
public void bind(Questions question) {
questionId = question.getId();
headerId = question.getHeaderId();
questionDescription.setText(question.getRank() + "." + question.getDescription());
if (question.isRequired()) {
imageRequired.setVisibility(View.VISIBLE);
}
if (question.isShowComment()) {
textViewComment.setVisibility(View.VISIBLE);
}
if (question.getHelpInfo().length() != 0 && !hasAnswers) {
tooltipHelpButton.setVisibility(View.VISIBLE);
TooltipCompat.setTooltipText(tooltipHelpButton, question.getHelpInfo());
questionDescription.setOnLongClickListener(view -> {
TooltipCompat.setTooltipText(questionDescription, question.getHelpInfo());
return false;
});
}
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
// Create radio buttons
radioGroup.removeAllViews();
int lastItem = -1;
for (Options option : question.getOptions()) {
RadioButton radioButton = new RadioButton(mContext);
radioButton.setText(option.getText());
radioButton.setId(option.getId());
setRadioButtonStyle(radioButton);
radioGroup.addView(radioButton, params);
if (hasAnswers) {
radioButton.setEnabled(false);
}
lastItem = radioGroup.getChildCount() - 1;
if (!hasAnswers) {
editTextComment.clearFocus();
Utils.hideKeyboardFrom(mContext, editTextComment);
int finalLastItem = lastItem;
radioGroup.setOnCheckedChangeListener((radioGroup, checkedId) -> {
if (radioButton.isChecked() && checkedId == radioGroup.getChildAt(finalLastItem).getId()) {
editTextOther.setVisibility(View.VISIBLE);
if (checkedId == radioGroup.getChildAt(finalLastItem).getId()) {
editTextOther.setVisibility(View.VISIBLE);
}
} else {
editTextOther.setVisibility(View.GONE);
}
checkedRadioButtonId = checkedId;
});
}
}
if (question.isShowOther() && !hasAnswers) {
radioGroup.getChildAt(lastItem).setVisibility(View.VISIBLE);
} else if (!question.isShowOther() && !hasAnswers) {
radioGroup.getChildAt(lastItem).setVisibility(View.GONE);
}
if (!hasAnswers) {
List<SurveyListHeader> headers = SurveyListHeader.selectAll(Utils.getDb(mContext), clientCode);
for (SurveyListHeader header : headers) {
String closedDate = header.getClosedDate();
ArrayList<SurveyListLines> surveyListLines = SurveyListLines.selectAll(Utils.getDb(mContext), headerId);
for (SurveyListLines surveyLine : surveyListLines) {
if (closedDate.equals("-1")) {
if (surveyLine.getQuestionId() == question.getId()) {
editTextComment.setText(surveyLine.getComments());
radioGroup.check(surveyLine.getOptionId());
questionDescription.setText(question.getRank() + "." + question.getDescription());
editTextOther.setText(surveyLine.getOther());
}
}
}
}
}
itemView.setOnClickListener(view -> {
editTextComment.clearFocus();
Utils.hideKeyboardFrom(mContext, editTextComment);
});
}
#Override
public void bindAnswers(List<Answers> answers) {
if (hasAnswers) {
if (answers != null) {
for (Answers currentAnswer : answers) {
for (AnswerLines currentLine : currentAnswer.getAnswerLines()) {
if (currentLine.getQuestionId() == questionId) {
radioGroup.check(currentLine.getOptionId());
if (!(currentLine.getComments() != null && currentLine.getComments().equals(""))) {
editTextComment.setVisibility(View.VISIBLE);
editTextComment.setText(currentLine.getComments());
} else {
editTextComment.setVisibility(View.GONE);
}
if (!(currentLine.getOther() != null && currentLine.getOther().equals(""))) {
editTextOther.setVisibility(View.VISIBLE);
editTextOther.setText(currentLine.getOther());
} else {
editTextOther.setVisibility(View.GONE);
RadioButton otherRadioButton = (RadioButton) radioGroup.getChildAt(radioGroup.getChildCount() - 1);
otherRadioButton.setVisibility(View.GONE);
}
}
}
}
}
}
}
public void setRadioButtonStyle(RadioButton radioButton) {
radioButton.setButtonDrawable(R.drawable.radiobutton_selector);
radioButton.setPadding(16, 16, 16, 16);
radioButton.setTextColor(ContextCompat.getColor(mContext, R.color.gray_medium));
}
#Override
public void isPressed(boolean isPressed) {
if (isPressed) {
SurveyListLines surveyLine = new SurveyListLines();
surveyLine.setQuestionId(questionId);
surveyLine.setOptionId(checkedRadioButtonId);
surveyLine.setComments(Objects.requireNonNull(editTextComment.getText()).toString());
surveyLine.setHeaderId(headerId);
surveyLine.setOther(Objects.requireNonNull(editTextOther.getText().toString()));
surveyLine.save(Utils.getDb(mContext));
}
}
}
I'm looking to find a right way how to implement the survey, I'm doing some research which of design patterns can fit for this kind of application. The only problem is to manage the send button from ViewPager, the user interface is fine. If anyone have some suggestions about this I would be glad to hear.
Thanks in advance.

How to manage multiple positions in RecyclerView OnClickListener

I want to know how I can get access to other elements of the array in this onclicklistener for a Recycler view. Specifically, I want to be able to change the enabled state of a position other than the current Listener position, but within the click event.
I'm trying to make it such that if three colors are checked (those are check boxes) every box not checked will be disabled until the number of boxes checked is < 3.
The for-loops I have I wrote make sense, but I can't programmatically change the enabled state within the onClickListener for some reason.
private void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
boolean checkedState;
if (mExampleList.get(position).getChecked1() == false) {
checkedState = true;
} else {
checkedState = false;
}
changeItem(position, checkedState);
int sum = 0;
for (int i = 0; i < stringArray.length; i++) {
Boolean checked = mExampleList.get(i).getChecked1();
if (checked == true) {
sum = sum + 1;
}
}
for (int i = 0; i < stringArray.length; i++) {
Boolean checked = mExampleList.get(i).getChecked1();
if (!checked && sum == 3) {
mExampleList.get(i).setEnabled1(false);
} else {
mExampleList.get(i).setEnabled1(true);
}
}
}
});
}
adapter
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public CheckBox mCheckBox;
public ExampleViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mCheckBox = itemView.findViewById(R.id.checkBox);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION);
listener.onItemClick(position);
}
}
});
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList) {
mExampleList = exampleList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mCheckBox.setText(currentItem.getCheckText());
holder.mCheckBox.setEnabled(currentItem.getEnabled1());
holder.mCheckBox.setChecked(currentItem.getChecked1());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
Item Class
public class ExampleItem {
public String mCheckText;
public Boolean mEnabled;
public Boolean mChecked;
public ExampleItem(String mCheckText, Boolean mEnabled, Boolean mChecked) {
this.mCheckText = mCheckText;
this.mEnabled = mEnabled;
this.mChecked = mChecked;
}
public ExampleItem(String mCheckText) {
this.mCheckText = mCheckText;
}
public String getCheckText() {
return mCheckText;
}
public void setCheckText(String mCheckText) {
this.mCheckText = mCheckText;
}
public Boolean getEnabled1() {
return mEnabled;
}
public void setEnabled1(Boolean mEnabled) {
this.mEnabled = mEnabled;
}
public Boolean getChecked1() {
return mChecked;
}
public void setChecked1(Boolean mChecked) {
this.mChecked = mChecked;
}
}
In other words, I am trying to make everything below blue disabled until I uncheck Red, Green, or Blue!
Try the following:
In adapter, add below codes:
private int selectedCount = 0;
public int getSelectedCount() {
return selectedCount;
}
public void setSelectedCount(int selectedCount) {
this.selectedCount = selectedCount;
notifyDataSetChanged();
}
and change onBindViewHolder() to:
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mCheckBox.setText(currentItem.getCheckText());
holder.mCheckBox.setChecked(currentItem.getChecked1());
if ((selectedCount == 3)) holder.mCheckBox.setEnabled(currentItem.getChecked1());
else holder.mCheckBox.setEnabled(true);
}
Then in Activity/Fragment, change mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener()... to:
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
boolean checkedState;
int selectedCount = mAdapter.getSelectedCount();
if ((selectedCount != 3) || (mExampleList.get(position).getChecked1())) {
if (mExampleList.get(position).getChecked1() == false) {
checkedState = true;
selectedCount++;
} else {
checkedState = false;
selectedCount--;
}
changeItem(position, checkedState);
mAdapter.setSelectedCount(selectedCount);
}
}
});
Pls note that no need to have mEnabled field in the ExampleItem class. Hope that helps!
Explanantion:
About the onClick:- This is because CheckBox totally covered the layout, so itemView cannot recieve the click event. About RecyclerView:- The idea is simple, after modified the data set [not list, here I refer to the mExampleList and also the selectedCount], then call notifyDataSetChanged() which will redraw all recycler item views.
You would need to create a setter function for your 'mExampleList' in your Adpater class, to update the dataset that the adapter is using. It obviously does not change anything, if you make changes to 'mExampleList' in your activity, without updating the list used by the Adapter.
So at the end of your click listener you would have something like that:
mAdapter.setExampleList(mExampleList)
mAdapter.notifyDataSetChanged()

Multiple selected items are not staying highlighted

When i choose an item from listview, it turns gray but when I select another item in the listview then the previous highlighted item turns to default color and the new item turns to gray. What I want is to stay both of them to be highlighted, and when a click on the highlighted items they should turn back to normal as well.
My code:
listView = (ListView) findViewById(R.id.conversationList);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new conversationsMultipleChoiceListener());
listView.setAdapter(conversationsAdapter);
((ConversationsAdapter) conversationsAdapter).updateConversations(conversationsList);
listView.setLongClickable(true);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Conversation item = (Conversation) conversationsAdapter.getItem(position);
startChat(item, false);
}
});
private class conversationsMultipleChoiceListener implements ListView.MultiChoiceModeListener {
#Override
public void onItemCheckedStateChanged(android.view.ActionMode mode, int position, long id, boolean checked) {
final int checkedCount = listView.getCheckedItemCount();
switch (checkedCount) {
case 0:
mode.setSubtitle(null);
break;
default:
mode.setSubtitle("" + checkedCount + " konuşma seçildi");
break;
}
}
#Override
public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.conversation_actions, menu);
mode.setTitle("Konuşmalarınız");
return true;
}
#Override
public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.sil:
Log.w("action","sil");
mode.finish();
break;
case R.id.blokla:
Log.w("action","blokla");
mode.finish();
break;
default:
break;
}
return true;
}
#Override
public void onDestroyActionMode(android.view.ActionMode mode) {
}
}
Adapter:
static class ViewHolder {
TextView nameView;
TextView bioView;
CircleImageView imageView;
TextView badge;
ProgressBar idleTimeBar;
public ImageView eyeView;
ImageView instagramVerified;
RelativeLayout badgeBg;
ImageView solOk;
TextView tarihText;
ImageView fotoIcon;
ImageView sesIcon;
}
public static class ConversationsAdapter extends BaseAdapter {
List<Conversation> conversations;
LayoutInflater inflater;
Context context;
private ConversationsAdapter(Context context, List<Conversation> conversations) {
this.conversations = conversations;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
public void updateConversations(List<Conversation> conversations) {
this.conversations = conversations;
notifyDataSetChanged();
}
#Override
public int getCount() {
return conversations.size();
}
#Override
public Conversation getItem(int position) {
return conversations.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.conversation_bars_v2, parent, false);
holder = new ViewHolder();
holder.nameView = (TextView) convertView.findViewById(R.id.nameText);
holder.badge = (TextView) convertView.findViewById(R.id.unreadMessageCount);
holder.bioView = (TextView) convertView.findViewById(R.id.bioText);
holder.imageView = (CircleImageView) convertView.findViewById(R.id.image);
holder.badgeBg = (RelativeLayout) convertView.findViewById(R.id.unreadMessageBg);
holder.solOk = (ImageView) convertView.findViewById(R.id.imageView22);
holder.tarihText = (TextView) convertView.findViewById(R.id.textView16);
holder.sesIcon = (ImageView) convertView.findViewById(R.id.imageView22);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Conversation item = conversations.get(position);
String name = item.getName();
String image_url = "http://application.domain.com/photos/profile/main/" + item.getPicture();
if (item.getLastMessage().equals("Fotoğraf")) {
holder.sesIcon.setImageResource(R.drawable.send_photo);
holder.sesIcon.setVisibility(View.VISIBLE);
}else if (item.getLastMessage().equals("Ses")) {
holder.sesIcon.setImageResource(R.drawable.send_voice_record);
holder.sesIcon.setVisibility(View.VISIBLE);
}else{
holder.sesIcon.setVisibility(View.INVISIBLE);
}
Long messageTimestamp = item.getLastMessageTime();
long nowTimestamp = timeHolder.toMillis(false);
Calendar messageTimeCal = Calendar.getInstance();
Calendar currentTimeCal = Calendar.getInstance();
messageTimeCal.setTimeInMillis(messageTimestamp);
currentTimeCal.setTimeInMillis(nowTimestamp);
boolean sameDay = messageTimeCal.get(Calendar.DAY_OF_YEAR) == currentTimeCal.get(Calendar.DAY_OF_YEAR) &&
messageTimeCal.get(Calendar.YEAR) == currentTimeCal.get(Calendar.YEAR);
boolean lastDay = messageTimeCal.get(Calendar.DAY_OF_YEAR) == currentTimeCal.get(Calendar.DAY_OF_YEAR) -1 &&
messageTimeCal.get(Calendar.YEAR) == currentTimeCal.get(Calendar.YEAR);
String dateText = "";
if (sameDay) {
//Mesaj bugün mü gönderildi?
SimpleDateFormat dateFormat1 = new SimpleDateFormat("HH:mm");
dateText = dateFormat1.format(messageTimeCal.getTime());
}else{
if (lastDay) {
//Bugün değilse mesaj dün mü gönderilmiş?
dateText = "Dün";
}else{
//Dün de değilse kaç gün önce gönderilmiş?
long diff = Math.abs(nowTimestamp - messageTimestamp);
int bolum = (int) (diff / (24 * 60 * 60 * 1000));
if (bolum <= 3) {
//Eğer geçen gün sayısı 3 veya daha az ise gün adını ekrana yaz
dateText = String.format("%tA", messageTimeCal);
}else{
//Yoksa direk tarihi yaz
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
dateText = dateFormat.format(messageTimeCal.getTime());
}
}
}
holder.tarihText.setText(dateText);
holder.nameView.setText(name);
if (item.getLastMessageFromMe() == 0) {
holder.bioView.setTextColor(Color.parseColor("#7A7A7A"));
//holder.solOk.setColorFilter(Color.parseColor("#666666"), android.graphics.PorterDuff.Mode.MULTIPLY); -- mehmet değiştirdi
holder.bioView.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL);
} else {
holder.bioView.setTextColor(Color.parseColor("#7A7A7A"));
//holder.solOk.setColorFilter(Color.parseColor("#A8A8B7"), android.graphics.PorterDuff.Mode.MULTIPLY); -- mehmet değiştirdi
holder.bioView.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL);
}
holder.bioView.setText(item.getLastMessage());
if (item.getLastMessage().equals("")) {
holder.bioView.setVisibility(View.GONE);
} else {
holder.bioView.setVisibility(View.VISIBLE);
}
if (item.getPicture().equals("default.jpg")) {
Picasso.with(context).load(R.drawable.default_picture).into(holder.imageView);
}else if (item.getPicture().equals("default_1.jpg")) {
Picasso.with(context).load(R.drawable.default_color_1).into(holder.imageView);
}else if (item.getPicture().equals("default_2.jpg")) {
Picasso.with(context).load(R.drawable.default_color_2).into(holder.imageView);
}else if (item.getPicture().equals("default_3.jpg")) {
Picasso.with(context).load(R.drawable.default_color_3).into(holder.imageView);
}else if (item.getPicture().equals("default_4.jpg")) {
Picasso.with(context).load(R.drawable.default_color_4).into(holder.imageView);
}else if (item.getPicture().equals("default_5.jpg")) {
Picasso.with(context).load(R.drawable.default_color_5).into(holder.imageView);
}else{
Picasso.with(context).load(image_url).into(holder.imageView);
}
holder.badge.setText(String.valueOf(item.getUnread()));
if (item.getUnread() != 0) {
holder.badgeBg.setVisibility(View.VISIBLE);
} else {
holder.badgeBg.setVisibility(View.GONE);
}
return convertView;
}
}
Listview xml:
<ListView
android:id="#+id/conversationList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="0dp"
android:layout_marginRight="10dp"
android:divider="#android:color/transparent"
android:dividerHeight="7.0sp"
android:scrollbars="none"
android:listSelector="#drawable/conversations_selector"></ListView>
How can i achive that functionality?
First, add a field conversationSelected in the Conversation class.
You should useRecyclerView instead of ListView.
You can refer to the official documentation to get started with RecyclerView.
When you have your RecyclerView, you can define the Adapter in this way:
public class ConversationAdapter extends RecyclerView.Adapter<ConversationAdapter.ViewHolder> {
List<Conversation> conversations;
public ConversationAdapter(List<Conversation> conversations) {
this.conversations = conversations;
}
public ConversationAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
TextView v = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_view, parent, false);
...
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Conversation conversation = conversations.get(position);
holder.mTextView.setText(conversation.getConversationText());
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return conversations.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public MyViewHolder(TextView v) {
super(v);
mTextView = v;
}
}
Next step: add item click listener to the RecyclerView: I struggled a little bit before see this answer which helps me to solve the problem: RecyclerView click Listener
In the clickListener you have to change the state conversationSelected of the Conversation in the conversations list (not inside the ViewHolder) to true.Then when you need to retrieve the selected conversation you have only to check this value.

SetExpandAdapter in RecycleViewAdapter

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;
}
}

Set Radiobutton true onItemclick on listview

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;
}
}

Categories

Resources