RecyclerView into ViewPager - How to change the appearance of elements - android

I have a test application.
The questions is uploaded to ViewPager. Each Viewpager element is a fragment. On the fragment there is TextView for question text and RecyclerView for answer options.
I need a button to appear when I select the answer option for the main activity. When you click on the button, the answers should be highlighted in red or green.
I can not understand how to implement the latter. How can I change the colour of a RecyclerView item from Activity?
The code allows you to select one or more options and highlight them.
My java classes:
public class QuestionActivity extends DaggerAppCompatActivity implements View.OnClickListener {
private QuestionViewModel viewModel;
private ViewPager questionsViewPager;
private TabLayout questionTabs;
private ProgressBar progressBar;
private TextView questionNumber;
private FloatingActionButton submitButton;
private OnQuestionListener onQuestionListener;
#Inject
ViewModelProviderFactory providerFactory;
#Inject
QuestionAdapter questionAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
questionsViewPager = findViewById(R.id.questionViewPager);
questionTabs = findViewById(R.id.questionTabLayout);
progressBar = findViewById(R.id.loadQuestionsProgressBar);
questionNumber = findViewById(R.id.questionNumberTextView);
submitButton = findViewById(R.id.submitFloatingActionButton);
onQuestionListener = questionAdapter;
submitButton.setOnClickListener(this);
viewModel = ViewModelProviders.of(this, providerFactory).get(QuestionViewModel.class);
Intent intent = getIntent();
Theme theme = intent.getParcelableExtra(Constants.THEME);
int themeId = theme.getThemeId();
initQuestionViewPager();
subscribeObservers(themeId);
}
#Override
public void onBackPressed() {
navThemeScreen();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
navThemeScreen();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void subscribeObservers(int themeId) {
viewModel.observeQuestions(themeId).observe(this, new Observer<Resource<List<Question>>>() {
#Override
public void onChanged(Resource<List<Question>> listResource) {
if (listResource != null) {
switch (listResource.status) {
case LOADING:
showProgress(true);
break;
case SUCCESS:
questionAdapter.setQuestions(listResource.data);
initTabs();
questionNumber.setText("Вопрос 1 из " + listResource.data.size());
showProgress(false);
break;
case ERROR:
showProgress(false);
Toast.makeText(QuestionActivity.this, listResource.message, Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void initQuestionViewPager() {
questionsViewPager.setAdapter(questionAdapter);
questionsViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
questionNumber.setText("Вопрос " + Integer.toString(position + 1) + " из " + questionsViewPager.getAdapter().getCount());
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void initTabs() {
questionTabs.setupWithViewPager(questionsViewPager, true);
for (int i = 0; i < questionsViewPager.getAdapter().getCount(); ++i) {
questionTabs.getTabAt(i).setText(Integer.toString(i + 1));
}
}
private void showProgress(boolean show) {
if (show) {
progressBar.setVisibility(View.VISIBLE);
}
else {
progressBar.setVisibility(View.GONE);
}
}
private void navThemeScreen() {
Intent intent = new Intent(QuestionActivity.this, ThemeActivity.class);
startActivity(intent);
finish();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submitFloatingActionButton:
onQuestionListener.onSubmitClick(questionsViewPager.getCurrentItem());
}
}
public interface OnQuestionListener {
void onSubmitClick(int questionNumber);
}
}
Fragment:
public class QuestionFragment extends Fragment implements View.OnClickListener,
OptionViewHolder.OnOptionListener, QuestionActivity.OnQuestionListener {
private View view;
private TextView questionText;
private RecyclerView options;
private FloatingActionButton submitButton;
private ViewPager viewPager;
private SingleQuestionViewModel viewModel;
private int position;
private Question question;
#Inject
ViewModelProviderFactory providerFactory;
#Inject
OptionAdapter optionAdapter;
public static QuestionFragment newInstance(int position) {
QuestionFragment fragment = new QuestionFragment();
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_question, container, false);
viewPager = (ViewPager) container;
position = getArguments().getInt("position");
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
AndroidSupportInjection.inject(this);
questionText = view.findViewById(R.id.questionTextTextView);
options = view.findViewById(R.id.optionsRecyclerView);
submitButton = view.findViewById(R.id.submitFloatingActionButton);
submitButton.setOnClickListener(this);
viewModel = ViewModelProviders.of(this, providerFactory).get(SingleQuestionViewModel.class);
question = viewModel.getQuestion(position);
initQuestion();
initOptions();
}
private void initQuestion() {
questionText.setText(question.getText());
}
private void initOptions() {
if (question.isMultipleAnswer()) {
optionAdapter.setMultiSelectionEnabled(true);
}
optionAdapter.setOptions(question.getOptions());
optionAdapter.setOnOptionListener(this);
options.setAdapter(optionAdapter);
options.setLayoutManager(new LinearLayoutManager(view.getContext()));
options.setHasFixedSize(true);
}
#SuppressLint("RestrictedApi")
private void showSubmitButton(boolean show) {
if (show) {
submitButton.setVisibility(View.VISIBLE);
}
else {
submitButton.setVisibility(View.GONE);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.submitFloatingActionButton:
boolean isCorrect = question.checkAnswers();
int currPos = viewPager.getCurrentItem();
new Handler().post(() -> viewPager.setCurrentItem(currPos + 1, true));
break;
}
}
#Override
public void onOptionSelected(OptionViewHolder v, SelectedOption selectedOption) {
}
#Override
public void onSubmitClick(int questionNumber) {
RecyclerView.ViewHolder test = options.getChildViewHolder(options.getChildAt(0));
optionAdapter.selectCorrectOptions();
}
class AnswerTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
question.setAnswers(optionAdapter.getSelectedOptions());
showSubmitButton(true);
return null;
}
}
}
Page adapter
public class QuestionAdapter extends FragmentStatePagerAdapter implements QuestionActivity.OnQuestionListener {
private List<Question> questions;
private HashMap<Integer, WeakReference<Fragment>> fragments;
private QuestionActivity.OnQuestionListener onQuestionListener;
public QuestionAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
questions = new ArrayList<>();
}
#Override
public int getCount() {
return questions.size();
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
fragments = new HashMap<>();
notifyDataSetChanged();
}
#NonNull
#Override
public Fragment getItem(int position) {
QuestionFragment fragment = new QuestionFragment().newInstance(position);
onQuestionListener = fragment;
return fragment;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
fragments.put(position, new WeakReference<>(fragment));
return fragment;
}
#Override
public void onSubmitClick(int questionNumber) {
onQuestionListener.onSubmitClick(questionNumber);
}
}
RecyclerViewAdpater
public class OptionAdapter extends RecyclerView.Adapter<OptionViewHolder> implements OptionViewHolder.OnOptionListener {
private List<SelectedOption> options;
private LayoutInflater layoutInflater;
private OptionViewHolder.OnOptionListener onOptionListener;
private boolean isMultiSelectionEnabled;
private HashMap<Integer, OptionViewHolder> holders;
public OptionAdapter() {
options = new ArrayList<>();
holders = new HashMap<>();
isMultiSelectionEnabled = false;
}
public void setOptions(List<Option> options) {
this.options.clear();
for(Option option : options) {
this.options.add(new SelectedOption(option, false));
}
notifyDataSetChanged();
}
public void setOnOptionListener(OptionViewHolder.OnOptionListener onOptionListener) {
this.onOptionListener = onOptionListener;
}
public void setMultiSelectionEnabled(boolean multiSelectionEnabled) {
isMultiSelectionEnabled = multiSelectionEnabled;
}
#NonNull
#Override
public OptionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.option_item, parent, false);
OptionViewHolder viewHolder = new OptionViewHolder(view, this);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull OptionViewHolder holder, int position) {
SelectedOption selectedOption = options.get(position);
holder.optionTextView.setText(selectedOption.getText());
if (isMultiSelectionEnabled) {
TypedValue typedValue = new TypedValue();
holder.optionTextView.getContext().getTheme().resolveAttribute(android.R.attr.listChoiceIndicatorMultiple, typedValue, true);
int checkMarkDrawableResId = typedValue.resourceId;
holder.optionTextView.setCheckMarkDrawable(checkMarkDrawableResId);
}
else {
TypedValue typedValue = new TypedValue();
holder.optionTextView.getContext().getTheme().resolveAttribute(android.R.attr.listChoiceIndicatorSingle, typedValue, true);
int checkMarkDrawableResId = typedValue.resourceId;
holder.optionTextView.setCheckMarkDrawable(checkMarkDrawableResId);
}
holder.selectedOption = selectedOption;
holder.setChecked(holder.selectedOption.isSelected());
holders.put(position, holder);
}
#Override
public int getItemCount() {
return options.size();
}
public List<Option> getSelectedOptions() {
List<Option> selectedOptions = new ArrayList<>();
for (SelectedOption option : options) {
if (option.isSelected()) {
selectedOptions.add(option);
}
}
return selectedOptions;
}
#Override
public int getItemViewType(int position) {
if (isMultiSelectionEnabled) {
return OptionViewHolder.MULTI_SELECTION;
}
else {
return OptionViewHolder.SINGLE_SELECTION;
}
}
#Override
public void onOptionSelected(OptionViewHolder v, SelectedOption selectedOption) {
if (!isMultiSelectionEnabled) {
for (SelectedOption option : options) {
if (!option.equals(selectedOption) && option.isSelected()) {
option.setSelected(false);
}
else if (option.equals(selectedOption) && selectedOption.isSelected()) {
option.setSelected(true);
}
}
}
notifyDataSetChanged();
onOptionListener.onOptionSelected(v, selectedOption);
}
public void selectCorrectOptions() {
for (Map.Entry<Integer, OptionViewHolder> entry : holders.entrySet()) {
entry.getValue().selectCorrectOptions();
}
notifyDataSetChanged();
}
}
ViewHolder
public class OptionViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public static final int SINGLE_SELECTION = 1;
public static final int MULTI_SELECTION = 2;
CheckedTextView optionTextView;
SelectedOption selectedOption;
OnOptionListener onOptionListener;
public OptionViewHolder(#NonNull View itemView, OnOptionListener onOptionListener) {
super(itemView);
this.onOptionListener = onOptionListener;
optionTextView = itemView.findViewById(R.id.optionTextView);
optionTextView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (selectedOption.isSelected() && getItemViewType() == MULTI_SELECTION) {
setChecked(false);
}
else {
setChecked(true);
}
onOptionListener.onOptionSelected(this, selectedOption);
}
public void setChecked(boolean checked) {
if (checked) {
optionTextView.setBackgroundColor(Color.parseColor("#66bfe8"));
}
else {
optionTextView.setBackground(null);
}
selectedOption.setSelected(checked);
optionTextView.setChecked(checked);
}
public void selectCorrectOptions() {
if (selectedOption.isSelected() && selectedOption.isCorrect()) {
optionTextView.setBackgroundColor(Color.parseColor("#007f00"));
}
else {
optionTextView.setBackground(null);
}
onOptionListener.onOptionSelected(this, selectedOption);
}
public interface OnOptionListener {
void onOptionSelected(OptionViewHolder v, SelectedOption selectedOption);
}
}

One way to solve this is to pass your item view to activity using interface. With your item view you can set background color or resource of your item.
So update your interface function with new parameter of type view and when you detect selection of item in your activity with interface, save the view reference and when the button is clicked, use that reference to set background.

Related

how to remove all items from RecyclerView on toolbar icon delete in android

Hello friend a lot of search but not working plz help me.
my probem is delete all history from adaptor using on toolbar delete icon how to remove adaptor data
below code first show adaptor and mainactivity
public void removehistory(View view)
button click to remove items from adaptor how to solve this problem sorry for bad english and advance thanks
HistoryAdaptor
public class HistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Object> data;
private GenCallback<HistoryModel> clickListener;
private static final int NATIVE_AD = 1;
private static final int HISTORY_ITEM = 2;
private LayoutInflater inflater;
// private Button removedata;
public HistoryAdapter() {
this.data = new ArrayList<>();
inflater = (LayoutInflater) App.getInstance().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case NATIVE_AD:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ad_unified, null, false);
return new NativeAdHolder(view);
case HISTORY_ITEM:
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false);
return new ViewHolder(view);
}
// return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_history, null, false));
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case NATIVE_AD:
((NativeAdHolder) holder).bind((UnifiedNativeAd) data.get(position));
break;
case HISTORY_ITEM:
default:
((ViewHolder) holder).bind((HistoryModel) data.get(position));
break;
}
}
#Override
public int getItemViewType(int position) {
if (data.get(position) instanceof UnifiedNativeAd) {
return NATIVE_AD;
} else {
return HISTORY_ITEM;
}
}
#Override
public int getItemCount() {
return data.size();
}
public void addItem(Object obj, int pos) {
this.data.add(pos, obj);
notifyItemInserted(pos);
}
public void updateData(ArrayList<HistoryModel> list) {
this.data.clear();
this.data.addAll(list);
notifyDataSetChanged();
}
public void clear() {
if (this.data != null && this.data.size() != 0) {
this.data.clear();
notifyDataSetChanged();
}
}
public void setClickListener(GenCallback<HistoryModel> clickListener) {
this.clickListener = clickListener;
}
public void showStarredOnly() {
/*Iterator<Object> iterator = data.iterator();
int pos = 0;
while (iterator.hasNext()) {
if (iterator.next() instanceof HistoryModel) {
HistoryModel historyModel = (HistoryModel) iterator.next();
if (!historyModel.isStarred()) {
iterator.remove();
// notifyItemRemoved(pos);
}
}
pos++;
}
notifyDataSetChanged();*/
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.tvFromLang)
TextView tvFromLang;
#BindView(R.id.tvFromText)
TextView tvFromText;
#BindView(R.id.tvToLang)
TextView tvToLang;
#BindView(R.id.tvToText)
TextView tvToText;
#BindView(R.id.ivStar)
ImageView ivStar;
#BindView(R.id.llMain)
CardView llMain;
#BindView(R.id.tvDate)
TextView tvDate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
llMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onCallback((HistoryModel) data.get(getAdapterPosition()));
}
}
});
llMain.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = getAdapterPosition();
HistoryModel historyModel = (HistoryModel) data.get(pos);
boolean isStar = historyModel.isStarred();
String from = historyModel.getFromLang();
String to = historyModel.getToLang();
Dialogs.INSTANCE.showActionsDialog(llMain.getContext(), isStar, from, to, new HistoryActionCallback() {
#Override
public void onClickCopyFrom() {
Utils.copyText(historyModel.getFromText());
Logger.logFabric(Constants.Events.COPY_FROM);
}
#Override
public void onClickCopyTo() {
Utils.copyText(historyModel.getToText());
Logger.logFabric(Constants.Events.COPY_TO);
}
#Override
public void onClickStar() {
Logger.logFabric(Constants.Events.MARKED_AS_FAV);
historyModel.setStarred(!isStar);
notifyItemChanged(pos);
RoomRepository.getNew().updateHistoryItem(historyModel);
// notifyDataSetChanged();
}
#Override
public void onClickDelete() {
String message = "Are you sure you want to delete?";
Dialogs.INSTANCE.showConfirmationDialog(view.getContext(), message, new View.OnClickListener() {
#Override
public void onClick(View view) {
RoomRepository.getNew().deleteHistoryRecord(historyModel.getTimeStamp());
data.remove(pos);
notifyItemRemoved(pos);
Dialogs.INSTANCE.dismissDialog();
Logger.logFabric(Constants.Events.ITEM_DELETED);
}
});
}
});
return false;
}
});
}
public void bind(HistoryModel item) {
StringBuilder builder = new StringBuilder();
builder.append(item.getFromLang()).append("(").append(item.getFromCode()).append(")");
tvFromLang.setText(builder);
tvFromText.setText(item.getFromText());
builder.setLength(0);
builder.append(item.getToLang()).append("(").append(item.getToCode()).append(")");
tvToLang.setText(builder);
tvToText.setText(item.getToText());
String date = Utils.formatDate(item.getTimeStamp(), "EEE, MMM d, yyyy");
tvDate.setText(date);
ivStar.setVisibility(item.isStarred() ? View.VISIBLE : View.GONE);
}
MainActivity
public class HistoryActivity extends AppCompatActivity {
private HistoryAdapter mAdapter;
private ArrayList<Object> data;
private Activity mCurrentActivity;
private RecyclerView rvHistory;
private Button clearh;
private GenCallback<HistoryModel> clickListener;
private ArrayList<HistoryModel> datamodel = new ArrayList<>();
private ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
rvHistory = findViewById(R.id.rvHistory);
ImageView imgb = findViewById(R.id.imgback);
initAdapter();
getAdapter();
imgb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HistoryActivity.super.onBackPressed();
}
});
}
private void getAdapter() {
RoomRepository.getNew().getAllHistory(mCallback);
}
private void initAdapter() {
mAdapter = new HistoryAdapter();
LinearLayoutManager layoutManager = new LinearLayoutManager(mCurrentActivity);
rvHistory.setLayoutManager(layoutManager);
rvHistory.setAdapter(mAdapter);
}
private IRoomDataHandler mCallback = new RoomDataHandler() {
#Override
public void onGetAllHistory(ArrayList<HistoryModel> list) {
// if (isSafe()) {
mAdapter.updateData(list);
// showLoader(false);
// checkForNoData();
// if (AdUtils.getInstance().getNativeAd() != null) {
//
// }
}
#Override
public void onError(String error) {
// showLoader(false);
// checkForNoData();
}
};
public void removehistory(View view) {
//problem is here
mAdapter.notifyItemRemoved(i);
}
}
call clear() method from on click oh that button like this.
public void removehistory(View view) {
//problem is here
mAdapter.clear()
}

How to sort a Recyclerview?

I am trying to sort the list of custom objects and display in Recyclerview. After displaying the items in recyclerview. I am sorting the list in the Activity and calling adapter.notifyDataSetChanged() but its not working.
Code in MainActivity.java:
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.notifyDataSetChanged();
Adapter code:
public class BeerListAdapter extends RecyclerView.Adapter<BeerListAdapter.MyViewHolder> {
private static ClickListener clickListener;
private Context context;
private LayoutInflater inflater;
private List<BeerData> beerDataList;
private List<BeerData> copyList;
public BeerListAdapter(Context context) {
this.context = context;
inflater = LayoutInflater.from(context);
beerDataList = new ArrayList<>();
copyList = new ArrayList<>();
}
public void setList(List<BeerData> beerDataList) {
if (this.beerDataList.isEmpty()) {
this.beerDataList.addAll(beerDataList);
copyList.addAll(beerDataList);
}
notifyDataSetChanged();
}
public void filter(String query) {
beerDataList.clear();
if (query.isEmpty()) {
beerDataList.addAll(copyList);
} else {
for (BeerData beerData : copyList) {
if (beerData.getName().replaceAll("[\\s]", "").toLowerCase().contains(query.replaceAll("[\\s]", "").toLowerCase())) {
beerDataList.add(beerData);
}
}
}
notifyDataSetChanged();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_beer_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.beerName.setText(beerDataList.get(position).getName());
holder.styleName.setText(beerDataList.get(position).getStyle());
holder.alcoholContent.setText("Alcohol Content: " + beerDataList.get(position).getAbv());
holder.quantity.setText(beerDataList.get(position).getQuantity().toString());
}
#Override
public int getItemCount() {
return beerDataList.size();
}
public void setOnItemClickListener(ClickListener clickListener) {
BeerListAdapter.clickListener = clickListener;
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView beerName, alcoholContent, styleName, quantity;
ImageView add, minus;
MyViewHolder(View itemView) {
super(itemView);
beerName = itemView.findViewById(R.id.beerName);
alcoholContent = itemView.findViewById(R.id.alcoholContent);
styleName = itemView.findViewById(R.id.beerStyle);
quantity = itemView.findViewById(R.id.quantity);
add = itemView.findViewById(R.id.add);
minus = itemView.findViewById(R.id.minus);
add.setOnClickListener(this);
minus.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
clickListener.onAddClick(getAdapterPosition(), v);
break;
case R.id.minus:
clickListener.onMinusClick(getAdapterPosition(), v);
break;
}
}
}
public interface ClickListener {
void onAddClick(int position, View v);
void onMinusClick(int position, View v);
}
}
Here is my MainActivity:
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener, LoginResultCallBack {
private static final String TAG = MainActivity.class.getSimpleName();
#Inject
MyApplication application;
LoginViewModel loginViewModel;
#BindView(R.id.beerListRecyclerView)
RecyclerView recyclerView;
#BindView(R.id.progressBar)
ProgressBar progressBar;
private BeerListAdapter adapter;
private List<BeerData> beerDataList;
private Menu menu;
private String sortType = "unsorted";
private Disposable networkDisposable;
List<BeerData> originalList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
((MyApplication) getApplication()).getComponent().inject(this);
loginViewModel = ViewModelProviders.of(this,new LoginViewModelFactory(application,this)).get(LoginViewModel.class);
adapter = new BeerListAdapter(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new BeerListAdapter.ClickListener() {
#Override
public void onAddClick(int position, View v) {
addItem(position);
}
#Override
public void onMinusClick(int position, View v) {
removeItem(position);
}
});
}
public void fetchData() {
progressBar.setVisibility(View.VISIBLE);
loginViewModel.fetchData();
loginViewModel.result.observe(this, new Observer<NetworkResponse>() {
#Override
public void onChanged(#Nullable NetworkResponse networkResponse) {
progressBar.setVisibility(View.GONE);
assert networkResponse != null;
if (networkResponse.getPostData() != null) {
beerDataList = new ArrayList<>();
originalList = networkResponse.getPostData();
beerDataList = networkResponse.getPostData();
Log.e(TAG, "Response: " + networkResponse.getPostData().get(0).getAbv());
progressBar.setVisibility(View.GONE);
adapter.setList(networkResponse.getPostData());
} else {
Log.e(TAG, "Response: " + networkResponse.getError().getLocalizedMessage());
progressBar.setVisibility(View.GONE);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
this.menu = menu;
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search Beer");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.cart:
Log.e(TAG, "cart clicked");
break;
case R.id.sort:
if (beerDataList != null) {
if (sortType.equalsIgnoreCase("unsorted")) {
Log.e(TAG,beerDataList.size()+" Size");
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.notifyDataSetChanged();
sortType = "ascend";
menu.getItem(2).setTitle(R.string.unsorted);
} else if (sortType.equalsIgnoreCase("ascend")) {
Log.e(TAG,beerDataList.size()+" Size");
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o2.getAbv().compareToIgnoreCase(o1.getAbv());
}
});
adapter.notifyDataSetChanged();
sortType = "descend";
menu.getItem(2).setTitle(R.string.view_original);
} else {
Log.e(TAG,beerDataList.size()+" Size");
beerDataList.clear();
beerDataList.addAll(originalList);
adapter.notifyDataSetChanged();
sortType = "unsorted";
menu.getItem(2).setTitle(R.string.sort);
}
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
#Override
protected void onResume() {
super.onResume();
networkDisposable = ReactiveNetwork.observeNetworkConnectivity(application)
.subscribeOn(Schedulers.io())
.filter(ConnectivityPredicate.hasState(NetworkInfo.State.CONNECTED))
.filter(ConnectivityPredicate.hasType(ConnectivityManager.TYPE_WIFI))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Connectivity>() {
#Override
public void accept(final Connectivity connectivity) {
// do something
if (connectivity.isAvailable()) {
fetchData();
} else {
Toast.makeText(MainActivity.this, R.string.internet_issue, Toast.LENGTH_LONG).show();
}
}
});
}
private void addItem(int position) {
int quantity = beerDataList.get(position).getQuantity();
quantity++;
beerDataList.get(position).setQuantity(quantity);
menu.getItem(1).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart_full));
adapter.notifyDataSetChanged();
}
private void removeItem(int position) {
if (beerDataList.get(position).getQuantity() > 0) {
int quantity = beerDataList.get(position).getQuantity();
quantity--;
if (quantity == 0)
menu.getItem(1).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart_empty));
beerDataList.get(position).setQuantity(quantity);
adapter.notifyDataSetChanged();
}
}
private void safelyDispose(Disposable... disposables) {
for (Disposable subscription : disposables) {
if (subscription != null && !subscription.isDisposed()) {
subscription.dispose();
}
}
}
#Override protected void onPause() {
super.onPause();
safelyDispose(networkDisposable);
}
#Override
public void onSuccess(String message) {
}
#Override
public void onError(String message) {
}
#Override
public void showProgress() {
}
#Override
public void hideProgress() {
}
}
What am I doing wrong here ?
You're not passing the sorted list to your adapter. You're just calling notifyDataSetChanged() which just tells the adapter that there is new data in its class and to use the baerDataList that is currently set within the class to refresh the list. Try this in your main activity.
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
adapter.setBeerDataList(beerDataList);
And setBeerDataList() in your adapter class.
private List<BeerData> beerDataList;
public void setBeerDataList(List<BeerData> sortedBeerDataList){
this.beerDataList = sortedBeerDataList;
notifyDataSetChanged();
}
Put sort function in MainActivity to BeerListAdapter:
private void sortBeer() {
Collections.sort(beerDataList, new Comparator<BeerData>() {
#Override
public int compare(BeerData o1, BeerData o2) {
return o1.getAbv().compareToIgnoreCase(o2.getAbv());
}
});
notifyDataSetChanged();
}
then call adapter.sortBeer() when do sort action

How to create an interface between a fragment and an adapter

I have been able to create an interface in the adapter to communicate with the fragment.
This is the adapter code
public class AgroInfoAdapter extends RecyclerView.Adapter<AgroInfoAdapter.ViewHolder> {
private Context mContext;
ArrayList<JsonObject> extensionItem = new ArrayList<>();
public Typeface tf;
public AgroInfoAdapter.AgroInfoAdapterListener listener;
public AgroInfoAdapter(Context context, ArrayList<JsonObject> extensionItem) {
this.extensionItem = extensionItem;
this.mContext = context;
this.tf = Typeface.createFromAsset(context.getAssets(), "FiraSans-Light.ttf");
}
#Override
public AgroInfoAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_crop_info, null);
AgroInfoAdapter.ViewHolder viewHolder = new AgroInfoAdapter.ViewHolder(itemLayoutView);
return viewHolder;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.header)
public TextView header;
#BindView(R.id.body)
public TextView body;
#BindView(R.id.thumbnail)
public ImageView thumbnail;
#BindView(R.id.button)
public Button button;
#BindView(R.id.downloadProgressView)
DownloadProgressView downloadProgressView;
#BindView(R.id.row)
public LinearLayout row;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
ButterKnife.bind(this, itemLayoutView);
}
}
#Override
public void onBindViewHolder(AgroInfoAdapter.ViewHolder viewHolder, final int position) {
try {
JsonObject sl = extensionItem.get(position);
viewHolder.header.setText(sl.get("title").getAsString());
if ((sl.get("title").getAsString()).equals("Land preparation")) {
viewHolder.button.setVisibility(View.VISIBLE);
}
Glide.with(mContext).load(CONFIG.IMAGE_URL+ sl.get("photo_url").getAsString())
.thumbnail(0.5f)
.apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.fallback(R.drawable.fallback)
.placeholder(R.drawable.progress_animation)
.error(R.drawable.fallback)
)
.into(viewHolder.thumbnail);
String description="";
for (JsonElement e:sl.get("description").getAsJsonArray()){
if(!e.getAsString().trim().isEmpty() && CharMatcher.javaUpperCase().or(CharMatcher.javaLetter().negate()).matchesAllOf(e.getAsString().trim())) {
SpannableString s1 = new SpannableString(e.getAsString());
s1.setSpan(new BulletSpan(20), 1, e.getAsString().length(), 0);
description +=s1 + "\n\n";
}else if(!e.getAsString().trim().isEmpty()) {
SpannableString s1 = new SpannableString(e.getAsString());
s1.setSpan(new BulletSpan(20), 1, e.getAsString().length(), 0);
description +=s1 + "\n\n";;
viewHolder.body.setText(description);
viewHolder.body.setTypeface(tf);
}
}
} catch (Exception e) {
}
applyClickEvents(viewHolder, position);
}
public interface AgroInfoAdapterListener {
void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position);
}
private void applyClickEvents(final AgroInfoAdapter.ViewHolder holder, final int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onCartRowClicked(view, holder.downloadProgressView, position);
}
});
}
#Override
public int getItemCount() {
return extensionItem.size();
}
}
This is the frgament which I was connecting to the adapter
AgroInfoAdapter adapter;
#BindView(R.id.rv)
RelativeLayout _RecyclerViewLayout;
#BindView(R.id.empty_rv)
RelativeLayout _EmptyRecyclerViewLayout;
#BindView(R.id.recycler_desc)
RecyclerView recyclerView;
Toolbar mToolbar;
#BindView(R.id.progress_bar)
ProgressBar progressBar;
#BindView(R.id.rv_layout) RelativeLayout relativeLayout;
ArrayList<JsonObject> ins = new ArrayList<>();
AgroInfoActivity.OnCropperSpinnerSelectedListener listener;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listener = new AgroInfoActivity.OnCropperSpinnerSelectedListener() {
#Override
public void onItemSelected(String pos) {
new LongOperation().execute(pos);
}
};
((AgroInfoActivity)getActivity()).addCropperSpinnerSelectedListener(listener);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_ext_land, container, false);
ButterKnife.bind(this,view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(1, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new AgroInfoAdapter(getActivity(), ins);
recyclerView.setAdapter(adapter);
return view;
}
#Override
public void onResume() {
new LongOperation().execute(((AgroInfoActivity)getActivity()).cropsSpinner.getSelectedItem().toString());
super.onResume();
}
private class LongOperation extends AsyncTask<String, Void, ArrayList<JsonObject>> {
#Override
protected ArrayList<JsonObject> doInBackground(String... params) {
try {
couchdbCropInfo = new CouchdbCropInfo(getActivity());
return couchdbCropInfo.allCropInfo(params[0],TYPE);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<JsonObject> result) {
ins.addAll(result);
adapter.notifyDataSetChanged();
if (ins.isEmpty()) {
_RecyclerViewLayout.setVisibility(View.GONE);
_EmptyRecyclerViewLayout.setVisibility(View.VISIBLE);
} else {
_RecyclerViewLayout.setVisibility(View.VISIBLE);
_EmptyRecyclerViewLayout.setVisibility(View.GONE);
}
relativeLayout.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
#Override
protected void onPreExecute() {
relativeLayout.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
ins.clear();
}
#Override
protected void onProgressUpdate(Void... values) {}
}
#Override
public void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position) {
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getActivity()
.getFragmentManager()
.beginTransaction();
Fragment fragmentB = new PostFragment();
fragmentB.setArguments(bundle);
fragmentTransaction.replace(R.id.parent, fragmentB);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
Basically what I am trying to achieve is I want to call a fragment when I click the button. The activity is a tablaout with about 5 fragments.
When I click the button. What brings about this and how best can I solve it or could have done it? Thanks in advance.
In place where you declare adapter or in the constructor of adapter, initiate the listener.
In the fragment side,
class Test extends Fragment {
AdapterClass adapter = new AdapterClass();
adapter.setListner(..)
view.setAdapter(adapter);
#Override
public void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position) {
}
}
In Adapter class
class AdapterClass {
private AgroInfoAdapterListener listner;
public setListner(AgroInfoAdapterListener listner) {
this.listner = listner;
}
public interface AgroInfoAdapterListener {
void onCartRowClicked(View view, DownloadProgressView downloadProgressView, int position);
}
private void applyClickEvents(final AgroInfoAdapter.ViewHolder holder, final int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}

Reordering issue in Staggered GridView Layout

I have an issue while using staggered GridView Layout. After I delete an element from the list, the item in the staggered gridview don't properly rearrange themselves. I mean, they leave lots of empty spaces above them.
Here are some pictures of before and after deleting,
before:
after:
one more:
But after I close the app and open it again, they reorder themselves properly.
Here is my code,
Fragment:
public class TaskListFragment extends Fragment {
public static final String TAG = TaskListFragment.class.getSimpleName();
private FragmentTaskListBinding mBinding;
private TaskViewModel viewModel;
private TaskListAdapter taskListAdapter;
private List<TaskEntity> entityList;
private StaggeredGridLayoutManager layoutManager;
public TaskListFragment() {
// Required empty public constructor
}
public static TaskListFragment instantiate() {
return new TaskListFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_task_list,
container, false);
mBinding.setFabClick(clickCallback);
layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mBinding.taskListRecyclerView.setItemAnimator(new DefaultItemAnimator());
mBinding.taskListRecyclerView.setLayoutManager(layoutManager);
return mBinding.getRoot();
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewModel = ViewModelProviders.of(this)
.get(TaskViewModel.class);
subscribeUi(viewModel);
}
private void subscribeUi(TaskViewModel viewModel) {
viewModel.loadTasks().observe(this, taskEntities -> {
if (taskEntities != null) {
setListData(taskEntities);
}
});
mBinding.executePendingBindings();
}
private void setListData(List<TaskEntity> taskEntities) {
this.entityList = taskEntities;
taskListAdapter = new TaskListAdapter();
taskListAdapter.setTaskList(entityList);
mBinding.taskListRecyclerView.setAdapter(taskListAdapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(createHelperCallback());
itemTouchHelper.attachToRecyclerView(mBinding.taskListRecyclerView);
}
private final FabClickCallback clickCallback = new FabClickCallback() {
#Override
public void onFabClick() {
if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
((MainListActivity) getActivity()).start();
}
}
};
private ItemTouchHelper.SimpleCallback createHelperCallback() {
return new SwipeToDelete() {
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
viewModel.deleteTask(entityList.get(position));
entityList.remove(position);
taskListAdapter.notifyItemRemoved(position);
}
};
}
}
Adapter:
public class TaskListAdapter extends RecyclerView.Adapter<TaskListAdapter.TaskViewHolder> {
private List<? extends Task> mTasks;
public TaskListAdapter() {
}
public void setTaskList(List<? extends Task> tasks) {
if (mTasks == null) {
mTasks = tasks;
notifyItemRangeInserted(0, mTasks.size());
} else {
DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {
#Override
public int getOldListSize() {
return mTasks.size();
}
#Override
public int getNewListSize() {
return tasks.size();
}
#Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return mTasks.get(oldItemPosition).getTId() ==
tasks.get(newItemPosition).getTId();
}
#Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
Task newTask = tasks.get(newItemPosition);
Task oldTask = mTasks.get(oldItemPosition);
return newTask.getTId() == oldTask.getTId()
&& Objects.equals(newTask.getTaskName(), oldTask.getTaskName())
&& Objects.equals(newTask.getTaskDescription(), oldTask.getTaskDescription());
}
});
mTasks = tasks;
result.dispatchUpdatesTo(this);
}
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
TaskItemBinding mBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.getContext()), R.layout.task_item,
parent, false);
return new TaskViewHolder(mBinding);
}
#Override
public void onBindViewHolder(TaskViewHolder holder, int position) {
holder.mBinding.setTask(mTasks.get(position));
}
#Override
public int getItemCount() {
return mTasks == null ? 0 : mTasks.size();
}
static class TaskViewHolder extends RecyclerView.ViewHolder {
final private TaskItemBinding mBinding;
public TaskViewHolder(TaskItemBinding taskItemBinding) {
super(taskItemBinding.getRoot());
mBinding = taskItemBinding;
}
}
}
Edit: I found the answer to my problem.
I've been creating a new adapter over and over and setting it to the recyclerview in setListData() method instead of putting them in onCreateView method. Moving those two lines of code to onCreateView fixed my issue.

Recycler View + Stars instead of Checkboxes: keeping state while scrolling

I'm having the usual problem with a list + a RecyclerView: when I change the resource file of an item (aka: selected/unselected star icon) and then scroll, other items of the list are keeping the same selected/unselected state for their own star. Plus, when I select an item and then go back, I'm missing the selected/unselected state.
The fullStar and the emptyStar are simple Android Vector images.
Here it is my ListFragment:
public class PetrolStationListFragment extends Fragment {
private RecyclerView mPetrolStationRecyclerView;
private PetrolStationAdapter mAdapter;
private int itemPosition;
public static boolean toBeCreated;
private static final String ARG_POSITION = "position";
// Design pattern to instantiate a new fragment.
public static PetrolStationListFragment newInstance(int position) {
PetrolStationListFragment fragment = new PetrolStationListFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
/********************************************************/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_petrol_station_list, container, false);
mPetrolStationRecyclerView = (RecyclerView) view.findViewById(R.id.petrol_recycler_view);
mPetrolStationRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
PetrolStationDAO petrolStationDAO = PetrolStationDAO.get(getActivity());
List<PetrolStation> petrolStations = petrolStationDAO.getPetrolStations();
if (mAdapter == null || toBeCreated) {
mAdapter = new PetrolStationAdapter(petrolStations);
mPetrolStationRecyclerView.setAdapter(mAdapter);
toBeCreated = false;
} else {
mAdapter.notifyItemChanged(itemPosition);
}
}
private class PetrolStationHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private PetrolStation mPetrolStation;
private TextView mNameTextView;
private TextView mAddressTextView;
private TextView mDistanceTextView;
private AppCompatImageView mStar;
private boolean mFavourite;
public PetrolStationHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mNameTextView = (TextView) itemView.findViewById(R.id.list_item_station_name_text_view);
mAddressTextView = (TextView) itemView.findViewById(R.id.list_item_station_address_text_view);
mDistanceTextView = (TextView) itemView.findViewById(R.id.list_item_station_distance_text_view);
mStar = (AppCompatImageView) itemView.findViewById(R.id.list_item_station_star_image_view);
mStar.setTag(R.id.list_item_station_star_image_view, "emptyStar");
}
public void bindPetrolStation(PetrolStation petrolStation) {
mPetrolStation = petrolStation;
mNameTextView.setText(mPetrolStation.getName());
mAddressTextView.setText("Via Verdi, 19/A");
mDistanceTextView.setText("300 meters");
mFavourite = mPetrolStation.isFavourite(mStar);
Log.d("FAVOURITE", "mFavourite: " + mFavourite);
//setStarByBoolean();
mStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setStarByTag();
}
});
}
#Override
public void onClick(View v) {
//itemPosition = mPetrolStationRecyclerView.getChildAdapterPosition(v);
Intent intent = PetrolStationPagerActivity.newIntent(getActivity(), mPetrolStation.getId());
startActivity(intent);
}
public void setStarByBoolean() {
if (!mFavourite) {
mStar.setImageResource(R.drawable.ic_star_border_orange);
mStar.setTag(R.id.list_item_station_star_image_view, "emptyStar");
} else {
mStar.setImageResource(R.drawable.ic_star_orange);
mStar.setTag(R.id.list_item_station_star_image_view, "fullStar");
}
}
public void setStarByTag() {
if (mStar.getTag(R.id.list_item_station_star_image_view).equals("emptyStar")) {
mStar.setImageResource(R.drawable.ic_star_orange);
mStar.setTag(R.id.list_item_station_star_image_view, "fullStar");
} else {
mStar.setImageResource(R.drawable.ic_star_border_orange);
mStar.setTag(R.id.list_item_station_star_image_view, "emptyStar");
}
}
}
private class PetrolStationAdapter extends RecyclerView.Adapter<PetrolStationHolder> {
private List<PetrolStation> mPetrolStations;
public PetrolStationAdapter(List<PetrolStation> petrolStations) {
mPetrolStations = petrolStations;
}
#Override
public PetrolStationHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item_petrol_station, parent, false);
return new PetrolStationHolder(view);
}
#Override
public void onBindViewHolder(PetrolStationHolder holder, int position) {
PetrolStation petrolStation = mPetrolStations.get(position);
Log.d("POSITION", "position: " + position);
holder.bindPetrolStation(petrolStation);
}
#Override
public int getItemCount() {
return mPetrolStations.size();
}
}
}
And here a the getter and the setter for the PetrolStation Model class:
public boolean isFavourite(AppCompatImageView star) {
if (star.getTag(R.id.list_item_station_star_image_view).equals("emptyStar")) {
mFavourite = false;
} else {
mFavourite = true;
}
return mFavourite;
}
public void setFavourite(boolean favourite) {
this.mFavourite = favourite;
}
Any hint about how to fix this issue? I'm finding difficult to apply the CheckBoxes examples I've found to my own case.

Categories

Resources