How to Add Long Click Context Menu To List Items - java

So first I initialized my listview and added registerForContextMenu(my_list)
chatLists = (ListView)findViewById(R.id.chatlist);
chatLists.setAdapter(new ContactListAdapter(this));
registerForContextMenu(chatLists);
Then I added the OnCreateContextMenu
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.chatlist) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.list_context, menu);
}
}
But After running the app.. When I long press on any list items, it's not showing any context Menu..

here is some sample code u can use:
`
... onCreateView{
.....
notiList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
setListMultiSelectListener();
}
public void setListMultiSelectListener() {
notiList.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// clear your list selection here
mAdapter.clearSelection();
}
#Override
public boolean onCreateActionMode(final ActionMode mode, Menu menu) {
// inflate your action menu here
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.delete_mode_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_select_all:
if (mAdapter.isAllSelected()) {
mAdapter.clearSelection();
for (int i = 0; i < notiList.getAdapter().getCount(); i++) {
notiList.setItemChecked(i, false);
}
} else {
mAdapter.selectAllItems();
for (int i = 0; i < notiList.getAdapter().getCount(); i++) {
notiList.setItemChecked(i, true);
}
}
break;
case R.id.action_delete:
mAdapter.deleteSelectedItems();
mode.finish();
break;
}
return true;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
deletionMode = mode;
if (checked) {
nr = nr + 1;
mAdapter.setNewSelection(position, checked);
} else {
nr = nr - 1;
mAdapter.removeSelection(position);
}
if (mAdapter.isAllSelected()) {
mode.getMenu().findItem(R.id.action_select_all).setIcon(R.drawable.check);
} else {
mode.getMenu().findItem(R.id.action_select_all).setIcon(R.drawable.uncheck);
}
}
});
}
`
here is adapter:
public class NotificationListAdapter extends BaseAdapter {
private MainActivity context;
private Vector<MessageInboxBean> messagesList;
private DisplayImageOptions /* options, */ options1;
private ImageLoader imageLoader;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private NotiItemHolder holder;
private boolean isHomeworkTab;
private LineColorPicker colorPicker;
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
int msgTypeId;
public NotificationListAdapter(MainActivity context, int msgTypeId, Vector<MessageInboxBean> messagesList, DisplayImageOptions options, boolean isHomeworkTab) {
this.context = context;
this.messagesList = messagesList;
// this.options = options;
options1 = new DisplayImageOptions.Builder()//
.showImageOnLoading(R.drawable.default_teacher)//
.showImageForEmptyUri(R.drawable.default_teacher)//
.showImageOnFail(R.drawable.default_teacher)//
.cacheInMemory(true)//
.cacheOnDisk(true)//
.considerExifParams(true)//
.displayer(new RoundedBitmapDisplayer(0))//
.build();
this.isHomeworkTab = isHomeworkTab;
this.msgTypeId = msgTypeId;
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
if (this.messagesList == null) {
messagesList = getMessagesList(this.msgTypeId);
}
// if (this.messagesList.size() == 0) {
// messagesList = getMessagesList(this.msgTypeId);
// }
}
public void setNewSelection(int position, boolean value) {
mSelection.put(position, value);
notifyDataSetChanged();
}
public boolean isPositionChecked(int position) {
Boolean result = mSelection.get(position);
return result == null ? false : result;
}
public Set<Integer> getCurrentCheckedPosition() {
return mSelection.keySet();
}
public void removeSelection(int position) {
mSelection.remove(position);
notifyDataSetChanged();
}
public void clearSelection() {
mSelection = new HashMap<Integer, Boolean>();
notifyDataSetChanged();
}
public void selectAllItems() {
mSelection = new HashMap<Integer, Boolean>();
for (int i = 0; i < messagesList.size(); i++) {
mSelection.put(i, true);
}
notifyDataSetChanged();
}
public boolean isAllSelected() {
if (mSelection.size() == messagesList.size()) {
return true;
} else {
return false;
}
}
public void deleteSelectedItems() {
ArrayList<Integer> notiIdAray = new ArrayList<Integer>();
for (int i = 0; i < messagesList.size(); i++) {
Boolean result = mSelection.get(i);
boolean result1 = result == null ? false : result;
if (result1) {
notiIdAray.add(messagesList.get(i).getNotificationId());
}
}
((MessageInboxTable) AppDb.getInstance(context).getTableObject(MessageInboxTable.TABLE_NAME)).deleteData(notiIdAray, context);
updateMessagesList(msgTypeId);
notifyDataSetChanged();
}
#Override
public int getCount() {
return messagesList.size();
}
#Override
public Object getItem(int position) {
return messagesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressWarnings("deprecation")
#SuppressLint({ "NewApi", "InflateParams" })
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.notification_list_item, null);
holder = new NotiItemHolder();
holder.dueDate = (TextView) convertView.findViewById(R.id.dueDateTxt);
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.day = (TextView) convertView.findViewById(R.id.day);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.message = (TextView) convertView.findViewById(R.id.message);
holder.subject = (TextView) convertView.findViewById(R.id.subject);
holder.doneStatus = (TextView) convertView.findViewById(R.id.doneStatus);
holder.sendersName = (TextView) convertView.findViewById(R.id.sendersName);
holder.notiDate = (TextView) convertView.findViewById(R.id.notiDate);
holder.sendersImg = (ImageView) convertView.findViewById(R.id.sendersImg);
holder.statusImg = (ImageView) convertView.findViewById(R.id.statusImg);
holder.star = (CheckBox) convertView.findViewById(R.id.star);
holder.doneLayout = (LinearLayout) convertView.findViewById(R.id.done_layout);
holder.endView = convertView.findViewById(R.id.endView);
convertView.setTag(holder);
} else {
holder = (NotiItemHolder) convertView.getTag();
}
MessageInboxBean bean = messagesList.get(position);
if (mSelection.get(position) != null) {
convertView.findViewById(R.id.cal_img_layout).setBackgroundResource(R.drawable.calender_check);
holder.dueDate.setVisibility(View.INVISIBLE);
holder.date.setVisibility(View.INVISIBLE);
holder.day.setVisibility(View.INVISIBLE);
} else {
if (bean.getDueDate().trim().length() > 0) {
convertView.findViewById(R.id.cal_img_layout).setBackgroundResource(R.drawable.calender);
holder.dueDate.setVisibility(View.VISIBLE);
holder.date.setVisibility(View.VISIBLE);
holder.day.setVisibility(View.VISIBLE);
holder.date.setText(getDueDate(bean.getDueDate()));
holder.day.setText(getDueDay(bean.getDueDate()));
} else {
convertView.findViewById(R.id.cal_img_layout).setBackgroundResource(R.drawable.calender_2);
holder.dueDate.setVisibility(View.INVISIBLE);
holder.date.setVisibility(View.INVISIBLE);
holder.day.setVisibility(View.INVISIBLE);
}
if (isHomeworkTab) {
holder.subject.setVisibility(View.VISIBLE);
holder.doneLayout.setVisibility(View.VISIBLE);
} else {
holder.subject.setVisibility(View.GONE);
holder.doneLayout.setVisibility(View.GONE);
}
}
holder.title.setText(bean.getTitle());
holder.message.setText(bean.getMessage());
if (isHomeworkTab) {
holder.subject.setText(getSubjectFromId(context, bean.getSubjectId()) == null ? "" : getSubjectFromId(context, bean.getSubjectId()));
String colr = getSubjectColorFromId(context, bean.getSubjectId());
if (colr != null) {
setColorToImage(holder.subject, 1, colr, false);
}
if (bean.getStatus().equals("0")) {
holder.doneStatus.setText("Not done");
holder.doneStatus.setTextColor(context.getResources().getColor(R.color.text_light_grey));
holder.statusImg.setImageResource(R.drawable.not_done);
} else {
holder.doneStatus.setText("Done");
holder.doneStatus.setTextColor(context.getResources().getColor(R.color.app_theme_color));
holder.statusImg.setImageResource(R.drawable.done);
}
}
holder.notiDate.setText(getMessageDate(bean.getMessageDate()));
if (bean.getStarred().equals("0")) {
holder.star.setChecked(false);
} else {
holder.star.setChecked(true);
}
holder.sendersName.setText("~" + bean.getSender());
// holder.notiDate
imageLoader.displayImage(bean.getSenderPicURL(), holder.sendersImg, options1, animateFirstListener);
holder.subject.setTag(position);
holder.star.setTag(position);
holder.doneLayout.setTag(position);
holder.subject.setOnClickListener(subjectClick);
holder.star.setOnCheckedChangeListener(starClick);
holder.doneLayout.setOnClickListener(doneClick);
if (position == getCount() - 1) {
holder.endView.setVisibility(View.VISIBLE);
} else {
holder.endView.setVisibility(View.GONE);
}
return convertView;
}
class NotiItemHolder {
TextView dueDate, date, day, title, message, subject, doneStatus, sendersName, notiDate;
ImageView sendersImg, statusImg;
CheckBox star;
LinearLayout doneLayout;
View endView;
}
}

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 can I change the colour of recyclerView item on button pressed?

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.

How to take the value of the checked row in list view, and get the prefered text field?

I fulfill the AlertDIalog and ListView with two values Name and id, and I cannot find conclusion оr the right way, when i checked some CheckBoxes, i need the value of the Checked/Selected rows of (id's text) to save.
#OnClick(R.id.group_delete)
void deleteGroup() {
AlertDialog.Builder dialog4 = new AlertDialog.Builder(PreviewActivity.this);
LayoutInflater inflater2 = getLayoutInflater();
View convertView2 = (View) inflater2.inflate(R.layout.alert_dialog_delete_group, null);
dialog4.setView(convertView2);
ListView listView2 = (ListView) convertView2.findViewById(R.id.listViewGroup);
final List<Item> groupList = this.getGroup();
CustomAdapter listAdapter2 = new CustomAdapter(getBaseContext(), groupList);
// listAdapter2.notifyDataSetChanged();
convertView2.setTag(dialog4);
// SparseBooleanArray sp = listView2.getCheckedItemPositions();
listView2.setOnItemClickListener((AdapterView<?> adapterView, View view, int position, long l) -> {
// Get user selected item.
Object itemObject = adapterView.getAdapter();
Item itemDto = (Item) itemObject;
CheckBox itemCheckbox = (CheckBox) convertView2.findViewById(R.id.checkMark5);
listAdapter2.setCheckedItem(position);
});
ImageView delete = (ImageView) convertView2.findViewById(R.id.del_group);
delete.setOnClickListener((View view) -> {
CheckBox itemCheckbox = (CheckBox) convertView2.findViewById(R.id.checkMark5);
Iterator<String> it = listAdapter2.getCheckedItems().values().iterator();
for (int i=0;i<listAdapter2.getCheckedItems().size();i++){
//Do whatever
// String result = "";
// ArrayList<String> resultList = new ArrayList<String>();
// for (int y = 0; y < resultList.size(); y++) {
// result += String.valueOf(resultList.get(i)) + "\n";
// }
// if (result.matches("")) {
////
// Toast.makeText(getApplicationContext(),"Please select some thing from list to show",Toast.LENGTH_LONG).show();
// }
// else {
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
// }
listAdapter2.getItem(Integer.parseInt(it.next()));
}
// List<Item> resultList = listAdapter2.getCheckedItems();
// for (int i = 0; i < resultList.size(); i++) {
// result += String.valueOf(resultList.get(i)) + "\n";
// }
// listAdapter2.getCheckedItemPositions().toString();
//
// if (result.matches("")) {
//
// Toast.makeText(getApplicationContext(),"Please select some thing from list to show",Toast.LENGTH_LONG).show();
// }
// else {
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
// }
// shared.setSharedPreferencesString(Constants.ID, size2);
listAdapter2.notifyDataSetChanged();
});
listView2.setAdapter(listAdapter2);
listView2.setTag(dialog4);
AlertDialog alert4 = dialog4.create();
alert4.show();
alert4.getWindow().
setBackgroundDrawable(new ColorDrawable(android.graphics.Color.argb(0, 100, 100, 100)));
}
public List<Company> getCompanies() {
return mCompanies;
}
private List<Item> getGroup() {
ArrayList<String> groups = new ArrayList<String>();
ArrayList<String> groups2 = new ArrayList<>();
for (Group group2 : mRepository.getCompanies().get(posit).getGroups()) {
groups2.add(group2.getId());
}
for (Group group1 : mRepository.getCompanies().get(posit).getGroups()) {
groups.add(group1.getName());
}
List<Item> ret = new ArrayList<Item>();
int length = groups.size();
for (int i = 0; i < length; i++) {
String itemText2 = groups.get(i);
String itemText3 = groups2.get(i);
Item dto = new Item();
dto.setChecked(false);
dto.setIdText(itemText3);
dto.setItemText(itemText2);
ret.add(dto);
}
return ret;
}
Item Class:
public class Item {
private boolean checked ;
private String itemText = "";
private String IdText = "";
private String IdText2 = "";
public String getIdText2() {
return IdText2;
}
public void setIdText2(String idText2) {
IdText2 = idText2;
}
public String getIdText() {
return IdText;
}
public void setIdText(String idText) {
IdText = idText;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getItemText() {
return itemText;
}
public void setItemText(String itemText) {
this.itemText = itemText;
}}
CustomAdapter :
public class CustomAdapter extends BaseAdapter {
private List<Item> ItemList ;
public HashMap<String, String> checked = new HashMap<String, String>();
private Context ctx;
public CustomAdapter(Context ctx, List<Item> ItemList) {
this.ctx = ctx;
this.ItemList = ItemList;
}
public void setCheckedItem(int item) {
if (checked.containsKey(String.valueOf(item))) {
checked.remove(String.valueOf(item));
} else {
checked.put(String.valueOf(item), String.valueOf(item));
}
}
public HashMap<String, String> getCheckedItems() {
return checked;
}
#Override
public int getCount() {
return ItemList.size();
}
#Override
public Object getItem(int position) {
return ItemList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
ItemViewHolder viewHolder = null;
if (convertView != null) {
viewHolder = (ItemViewHolder) convertView.getTag();
} else {
convertView = View.inflate(ctx, R.layout.custom, null);
CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.checkMark5);
TextView listItemText = (TextView) convertView.findViewById(R.id.item_unit_id5);
TextView tetx = (TextView) convertView.findViewById(R.id.tekst5);
TextView textId = (TextView) convertView.findViewById(R.id.item_number5);
viewHolder = new ItemViewHolder(convertView);
viewHolder.setItemCheckbox(checkbox);
viewHolder.setItemTextView(listItemText);
viewHolder.setIdTextView(textId);
viewHolder.setIdTextView2(tetx);
convertView.setTag(viewHolder);
}
Item items = ItemList.get(position);
viewHolder.getItemCheckbox().setChecked(items.isChecked());
viewHolder.getItemTextView().setText(items.getItemText());
viewHolder.getIdTextView().setText(items.getIdText());
viewHolder.getIdTextView2().setText(items.getIdText2());
return convertView;
}}
ViewHolder :
public class ItemViewHolder extends RecyclerView.ViewHolder {
private CheckBox itemCheckbox;
private TextView IdTextView;
private TextView itemTextView;
private TextView IdTextView2;
public TextView getIdTextView2() {
return IdTextView2;
}
public void setIdTextView2(TextView idTextView2) {
IdTextView2 = idTextView2;
}
public ItemViewHolder(View itemView) {
super(itemView);
}
public TextView getIdTextView() {
return IdTextView;
}
public void setIdTextView(TextView idTextView) {
IdTextView = idTextView;
}
public CheckBox getItemCheckbox() {
return itemCheckbox;
}
public void setItemCheckbox(CheckBox itemCheckbox) {
this.itemCheckbox = itemCheckbox;
}
public TextView getItemTextView() {
return itemTextView;
}
public void setItemTextView(TextView itemTextView) {
this.itemTextView = itemTextView;
} }

Can't Open Context Menu on Click of Menu Button in Android

I have a problem with the contextual menu, I have to control "MenuButton" without using of "Contextual Action bar menu (CAB)" when you make a long click and short click displays a context menu.I need to display the contextual menu with using of "Contextual Action bar menu (CAB)".when you make short click on "MenuButton" CAB menu also called on a short click, not a long click. I need to display the contextual menu with a short click. is this possible?
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_internal);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
title = (TextView) findViewById(R.id.txt_name_file);
past = (ImageView) findViewById(R.id.img_paste);
home = (ImageView) findViewById(R.id.img_home);
menu_item = (ImageView) findViewById(R.id.img_more);
list_in = (ListView) findViewById(R.id.list_in);
past.setVisibility(View.INVISIBLE);
fileManager = new FileManager();
arrayList = new ArrayList<>();
adapter = new InternalAdapter(getApplicationContext(), arrayList);
list_in.setAdapter(adapter);
list_in.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
if (selectCount > 0) {
if (actionMode == null) {
actionMode = InternalActivity.this.startActionMode(callback);
Toast.makeText(getApplicationContext(), "S>0", Toast.LENGTH_SHORT).show();
}
toggleselection(i);
actionMode.setTitle(selectCount + " " + "Selected");
if (selectCount == 0) {
actionMode.finish();
}
} else if (selectCount == 0) {
Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
String S = arrayList.get(i).getPathFile();
File file = new File(S);
if (arrayList.get(i).isFile() == false) {
pathItem = arrayList.get(i).getPathFile();
title.setText(pathItem.substring(pathItem.lastIndexOf("/") + 1));
readFile(pathItem);
} else if (file.canRead()) {
Intent intent = FileManager.createIntent(file);
if (getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
}
}
});
list_in.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (actionMode == null) {
actionMode = InternalActivity.this.startActionMode(callback);
Toast.makeText(getApplicationContext(), "L", Toast.LENGTH_SHORT).show();
}
toggleselection(position);
actionMode.setTitle(selectCount + " " + "Selected");
if (selectCount == 0) {
actionMode.finish();
}
return true;
}
});
readFile(FileManager.PATH);
loadFileItem();
}
ArrayList<FileItem> selectedFile = new ArrayList<>();
private void toggleselection(int position) {
arrayList.get(position).isSelected = !arrayList.get(position).isSelected;
if (arrayList.get(position).isSelected) {
selectedFile.add(arrayList.get(position));
selectCount++;
} else {
selectedFile.add(arrayList.get(position));
selectCount--;
}
adapter.notifyDataSetChanged();
}
private ActionMode.Callback callback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater menuInflater = mode.getMenuInflater();
menuInflater.inflate(R.menu.internal_context_menu, menu);
MenuItem mi = menu.getItem(0);
mi.setTitle(mi.getTitle().toString());
actionMode = mode;
selectCount = 0;
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.i_de:
mode.finish();
break;
}
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
if (selectCount > 0) {
deSelect();
}
actionMode = null;
}
};
private void deSelect() {
for (int i = 0; i < arrayList.size(); i++) {
arrayList.get(i).isSelected = false;
}
selectCount = 0;
adapter.notifyDataSetChanged();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.select_file, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.copy:
copyFolder(pos);
break;
case R.id.delete:
deleteFolder(pos);
break;
case R.id.rename:
renameFile(pos);
break;
}
return super.onContextItemSelected(item);
}
public class InternalAdapter extends BaseAdapter {
ArrayList<FileItem> arrayList;
Context context;
ViewHolder viewHolder;
public InternalAdapter(Context context, ArrayList<FileItem> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public FileItem getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
viewHolder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.activity_internal_adapter, parent, false);
viewHolder.imgFolder = (ImageView) view.findViewById(R.id.img_folder);
viewHolder.txtNameFile = (TextView) view.findViewById(R.id.txt_name_folder);
viewHolder.txtDate = (TextView) view.findViewById(R.id.txt_date);
viewHolder.imgCreate = (ImageView) view.findViewById(R.id.img_create);
viewHolder.view = view.findViewById(R.id.view_internal);
viewHolder.linearLayout = (LinearLayout) view.findViewById(R.id.lv_image);
FileItem fileItem = getItem(position);
if (fileItem.isSelected) {
viewHolder.view.setAlpha(0.5f);
} else {
viewHolder.view.setAlpha(0.0f);
}
if (fileItem.isDirectory()) {
viewHolder.imgFolder.setImageResource(R.drawable.ic_folder_black_24dp);
} else if (fileItem.isFile()) {
viewHolder.imgFolder.setImageResource(R.drawable.ic_insert_drive_file_black_24dp);
}
viewHolder.txtNameFile.setText(fileItem.getName());
viewHolder.txtDate.setText(fileItem.getDate());
viewHolder.imgCreate.setLongClickable(false);
registerForContextMenu(viewHolder.imgCreate);
viewHolder.imgCreate.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
unregisterForContextMenu(v);
Toast.makeText(getApplicationContext(), "111", Toast.LENGTH_SHORT).show();
return false;
}
});
viewHolder.imgCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pos = position;
openContextMenu(v);
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show();
}
});
return view;
}
private class ViewHolder {
ImageView imgFolder;
TextView txtNameFile;
TextView txtDate;
ImageView imgCreate;
View view;
LinearLayout linearLayout;
}
}
}

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

Categories

Resources