Actually this screen displays a set of questions and the task is to read the user entered or selected answer.
So the my question is, how to get the value from ChooseAdapter to QuestionAdapter and then get all the value from QuestionAdapter to my Activity.
My english is little bit weak, sorry for that.
And thanks in advance.
Main adapter : QuestionAdapter.java
public class QuestionsAdapter extends RecyclerView.Adapter<QuestionsAdapter.RecyclerViewHolder> {
private ArrayList<Question> mRecyclerViewItems;
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final String TAG = QuestionsAdapter.class.getSimpleName();
private static Context mContext;
private NetworkManager nm;
private boolean visibility = false;
private ChoiceAdapter adapter;
private ArrayList<QuestionsAnswer> questionsAnswers = new ArrayList<>();
ArrayList<ChoiceAnswer> choiceAnswers;
public QuestionsAdapter(Context context, ArrayList<Question> recyclerViewItems) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//this view contains recycler view under recycler view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
default:
final RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder;
Question data = (Question) mRecyclerViewItems.get(position);
try {
recyclerViewHolder.txtQuestion.setText(data.getQuestion());
recyclerViewHolder.txtQuestionType.setText(data.getQuestionType());
if (data.getQuestionType().equals("MULT")) {
recyclerViewHolder.mRecyclerChoice.setVisibility(View.VISIBLE);
recyclerViewHolder.edtQuestion.setVisibility(View.GONE);
if (data.getChoices().size() > 0) {
adapter = new ChoiceAdapter(mContext, data.getChoices(), position);
recyclerViewHolder.mRecyclerChoice.setAdapter(adapter);
}
} else {
recyclerViewHolder.mRecyclerChoice.setVisibility(View.GONE);
recyclerViewHolder.edtQuestion.setVisibility(View.VISIBLE);
}
recyclerViewHolder.btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (data.getQuestionType().equals("MULT")) {
Log.v(TAG, "array Data : " + adapter.getChoiceAnswer());
} else {
Log.v(TAG, "array Data : " + recyclerViewHolder.edtQuestion.getText().toString());
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView txtQuestion,txtQuestionType;
EditText edtQuestion;
RecyclerView mRecyclerChoice;
Button btnOk;
private LinearLayoutManager linearLayoutManager;
public RecyclerViewHolder(View view) {
super(view);
txtQuestion = view.findViewById(R.id.txt_question);
edtQuestion = view.findViewById(R.id.edt_question);
mRecyclerChoice = view.findViewById(R.id.recycler_choice);
btnOk = view.findViewById(R.id.btn_ok);
txtQuestionType = view.findViewById(R.id.txt_question_type);
initRecyclerView();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtQuestionType.getText().toString().equals("MULT")) {
Log.v(TAG, "array Data : " + adapter.getChoiceAnswer());
} else {
Log.v(TAG, "array Data : " + edtQuestion.getText().toString());
}
}
});
}
private void initRecyclerView() {
//setting properties of recyclerView
mRecyclerChoice.setHasFixedSize(true);
mRecyclerChoice.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(mContext);
mRecyclerChoice.setLayoutManager(linearLayoutManager);
}
}
public static void validation() {
Toast.makeText(mContext, "testing", Toast.LENGTH_SHORT).show();
}}
for list of CheckBox : ChooseAdapter.java
public class ChoiceAdapter extends RecyclerView.Adapter<ChoiceAdapter.RecyclerViewHolder> {
private ArrayList<Choice> mRecyclerViewItems;
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final String TAG = ChoiceAdapter.class.getSimpleName();
private Context mContext;
private NetworkManager nm;
// private OnItemClickListener mOnItemClickListener;
private boolean visibility = false;
private static ArrayList<ChoiceAnswer> choiceAnswerArrayList;
private ChoiceAnswer choiceAnswer;
String arrayData;
public ChoiceAdapter(Context context, ArrayList<Choice> recyclerViewItems, int position) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
// choiceAnswer.key = 0;
choiceAnswerArrayList = new ArrayList<>();
//initializing choiceAnswer
choiceAnswer = new ChoiceAnswer();
choiceAnswer.values = new ArrayList<>();
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//this view contains recycler view under recycler view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio_button, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
default:
final RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder;
Choice data = (Choice) mRecyclerViewItems.get(position);
try {
recyclerViewHolder.checkChoice.setText(data.getChoiceName());
recyclerViewHolder.checkChoice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
arrayData = "";
for (int i = 0; i < mRecyclerViewItems.size(); i++) {
if (isChecked) {
if (!choiceAnswer.values.contains(data.getChoiceID())) {
choiceAnswer.values.add(i, data.getChoiceID());
}
} else {
choiceAnswer.values.remove(data.getChoiceID());
// arrayData = choiceAnswer.values.toString().replace("[", "").replace("]", "").trim();
}
try {
arrayData = arrayData + "," + choiceAnswer.values.get(i);
}catch (IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public String getChoiceAnswer() {
return arrayData;
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
CheckBox checkChoice;
public RecyclerViewHolder(View view) {
super(view);
checkChoice = view.findViewById(R.id.check_choice);
}
}}
Please help me guys I am trying this since last 3 days...
I've implemented my own login too, but it didn't working properly.
Related
I am doing an app which auto-scrolls images, at the bottom of the screen there is a static layout, which I need to display the value of images that have already passed (i.e. position).
I get the correct value of images passed by implementing :
int position = holder.getAdapterPosition();
in the RecyclerViewListAdapter.java
now I need to display this value in the RecyclerViewListActivity.java
on a text view at the static layout beneath the Recycler view?
public class RecyclerViewListAdapter extends RecyclerView.Adapter {
Context context;
List<Data> dataList;
private SharedPreferences preferences;
public RecyclerViewListAdapter(Context context, List<Data> dataList) {
this.context = context;
this.dataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_recycler_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.mImage.setImageResource(dataList.get(position).getImage());
holder.mImage.setImageResource(dataList.get(position).getImage());
**int position = holder.getAdapterPosition();**
}
#Override
public int getItemCount() {
if (dataList == null || dataList.size() == 0)
return 0;
return dataList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView mNumberText,mText;
ImageView mImage;
LinearLayout mLinearLayout;
public MyViewHolder(View itemView) {
super(itemView);
mImage = (ImageView) itemView.findViewById(R.id.quran_page);
mLinearLayout = (LinearLayout) itemView.findViewById(R.id.linearLayout);
}
}
}
public class RecyclerViewListActivity extends AppCompatActivity {
RecyclerView mListRecyclerView;
ArrayList<Data> dataArrayList;
RecyclerViewListAdapter recyclerViewListAdapter ;
Runnable updater;
private boolean isTouch = false;
TextViewRemaining;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view_list);
final TextView TextViewRemaining = (TextView) findViewById(R.id.TextViewRemaining);
**TextViewRemaining.setText("Position: "+position);**
initializeView();
mListRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
mListRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(RecyclerViewListActivity.this, "Long press on position :" + position,
Toast.LENGTH_LONG).show();
}
}));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public static interface ClickListener{
public void onClick(View view,int position);
public void onLongClick(View view,int position);
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
//#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){
clicklistener.onClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
private void initializeView()
{
mListRecyclerView = (RecyclerView) findViewById(R.id.vR_recyclerViewList);
setValues();
}
private void setValues(){
prepareData();
recyclerViewListAdapter = new RecyclerViewListAdapter(RecyclerViewListActivity.this,dataArrayList);
mListRecyclerView.setLayoutManager(new LinearLayoutManager(RecyclerViewListActivity.this)); // original
mListRecyclerView.setItemAnimator(new DefaultItemAnimator());
mListRecyclerView.setHasFixedSize(false);
mListRecyclerView.setAdapter(recyclerViewListAdapter);
recyclerViewListAdapter.notifyDataSetChanged();
final int speedScroll = 2000; //default is 2000 it need to be 30000
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
int count = 0;
// boolean flag = true;
#Override
public void run() {
boolean x=true;
// while(x) {
if (count < recyclerViewListAdapter.getItemCount()) {
if (count == recyclerViewListAdapter.getItemCount() - 1) {
flag = false;
} else if (count == 0) {
flag = true;
}
}
if (flag) count++;
// else count--;
mListRecyclerView.smoothScrollToPosition(count);
handler.postDelayed(this, speedScroll);
}
};
handler.postDelayed(runnable,speedScroll);
}
private void prepareData(){
dataArrayList = new ArrayList<>();
Data data1 = new Data();
data1.setImage(R.drawable.p1);
dataArrayList.add(data1);
Data data2 = new Data();
data2.setImage(R.drawable.p2);
dataArrayList.add(data2);
Data data3 = new Data();
data3.setImage(R.drawable.p3);
dataArrayList.add(data3);
Data data4 = new Data();
data4.setImage(R.drawable.p4);
dataArrayList.add(data4);
Data data5 = new Data();
data5.setImage(R.drawable.p5);
dataArrayList.add(data5);
}
}
So, How can I show the position value on textView in a real-time, as position is a dynamic value, I expect the output on the textView to change as the images passed to the top.
Many Thanks in advance.
This how I solve my problem:
I save the position value in a power Preference(an easier version of shared Preferences)-many thanks to:
Ali Asadi(https://android.jlelse.eu/powerpreference-a-simple-approach-to-store-data-in-android-a2dad4ddc4ac)
I use a Thread that updates the textview every second-many thanks to:
https://www.youtube.com/watch?v=6sBqeoioCHE&t=149s
Thanks for all.
I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}
Hello I am trying to implement multi select in recycler view android for showing an icon when clicked on that particular view, I have tried the below code and is working fine for that particular position, however there are other several views that too are getting updated, so please check and let me know what am I missing
Here is my adapter code:
public class ContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
Context context;
ArrayList<String> alContactName, alContactEmail, alContactNumber;
ArrayList<Boolean> alFromLinkedIn;
int mergeFlag=0;
private static SparseBooleanArray selectedItems;
ArrayList<Integer> alSelectedPositions;
public ContactsAdapter(Context context, ArrayList<String> alContactName, ArrayList<String> alContactEmail, ArrayList<String> alContactNumber, ArrayList<Boolean> alisFromLinkedIn) {
//Include one more variable for checking type i.e linked in or normal contact
super();
this.context = context;
this.alContactName = alContactName;
this.alContactEmail = alContactEmail;
this.alContactNumber = alContactNumber;
this.alFromLinkedIn = alisFromLinkedIn;
alSelectedPositions=new ArrayList<>();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_merge_contact, parent, false);
return new ContactsHolder(view);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
try {
((ContactsHolder) holder).relMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alSelectedPositions.add(position);
notifyDataSetChanged();
}
});
if(alSelectedPositions.get(position)==position){
((ContactsHolder) holder).imgMerge.setVisibility(View.VISIBLE);
}
else {
((ContactsHolder) holder).imgMerge.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
check updated code. I have modified the #tahsinRupam code.
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
try {
((ContactsHolder) holder).relMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(alSelectedPositions.size>0)
{
for(int i=0;i<a1SelectedPositions.size;i++)
{
//if you want to cleasr previous details of array
if(a1SelectedPositions.contains(position))
alSelectedPositions.remove(position);
else
alSelectedPositions.add(position);
}
}
else
{
alSelectedPositions.add(position);
notifyDataSetChanged();
}
});
//update the position on scroll
for(int i=0;i<a1SelectedPositions.size;i++)
{
if(alSelectedPositions.get(i)==position){
((ContactsHolder)holder).imgMerge.setVisibility(View.VISIBLE);
}
else {
((ContactsHolder) holder).imgMerge.setVisibility(View.GONE);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Recently I had to implement a multi select RecyclerView, below I attached a simplified code snippet for a clean way to implement multi-select feature in RecyclerView:
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> implements IMultiSelectableList<Item> {
boolean selectionMode = false;
HashSet<Item> selectedItems;
ArrayList<Item> mItems;
public ItemAdapter(ArrayList<Item> Items) {
super();
selectedItems = new HashSet<>();
mItems = Items;
}
public void enterSelectionModeWithItem(int selectedItemPosition){
if(selectedItemPosition >= 0 && selectedItemPosition < mItems.size())
selectedItems.add(mItems.get(selectedItemPosition));
selectionMode = true;
notifyDataSetChanged();
}
public void clearSelectionMode() {
selectionMode = false;
selectedItems.clear();
notifyDataSetChanged();
}
public class ItemHolder extends RecyclerView.ViewHolder{
ImageView mImage;
public ItemHolder(View itemView) {
super(itemView);
mImage = itemView.findViewById(R.id.image);
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if(!selectionMode){
int selectedPosition = getAdapterPosition();
Item selectedItem = mItems.get(selectedPosition);
enterSelectionModeWithItem(selectedItem);
return true;
}
return false;
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int selectedPosition = getAdapterPosition();
Item selectedItem = mItems.get(selectedPosition);
//Capture Clicks in Selection Mode
if(selectionMode){
if(selectedItems.contains(selectedItem)){
selectedItems.remove(selectedItem);
mImage.setImageResource(R.drawable.ic_checkbox_blank_circle_outline_grey600_48dp);
} else {
selectedItems.add(selectedItem);
mImage.setImageResource(R.drawable.ic_checkbox_marked_circle_grey600_48dp);
}
}
}
});
}
public void setupView(Item item){
if(selectionMode){
if(selectedItems.contains(item)){
mImage.setImageResource(R.drawable.ic_checkbox_marked_circle_grey600_48dp);
} else {
mImage.setImageResource(R.drawable.ic_checkbox_blank_circle_outline_grey600_48dp);
}
}
}
#Override
public ItemAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_item, parent, false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(ItemAdapter.ItemHolder holder, int position) {
holder.setupView(mItems.get(position));
}
#Override
public int getItemCount() {
return mItems != null ? mItems.size() : 0;
}
}
, I use an image to show selection like Gmail app but feel free to use whatever works for you (background color, font style, etc).
P.S: I designed a callback interface for a simple selection interactions, if it helps I can attach it too! Cheers!
You've to do some specific things:
Initialize an int type array (type can be different) and assign 0 value to all it's elements.
int[] selectedPos = null;
public ContactsAdapter(Context context, ArrayList<String> alContactName, ArrayList<String> alContactEmail, ArrayList<String> alContactNumber, ArrayList<Boolean> alisFromLinkedIn) {
//Include one more variable for checking type i.e linked in or normal contact
super();
this.context = context;
this.alContactName = alContactName;
this.alContactEmail = alContactEmail;
this.alContactNumber = alContactNumber;
this.alFromLinkedIn = alisFromLinkedIn;
alSelectedPositions=new ArrayList<>();
for(int i = 0 ; i < alContactName.size() ; i++)
selectedPos[i] = 0;
}
Store the selected positions in selectedPos.
Then, check if the position is selected and set visibility accordingly:
In onBindViewHolder() add the following code:
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
try {
((ContactsHolder) holder).relMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPos[position] = 1;
notifyDataSetChanged();
}
});
} catch (Exception e) {
e.printStackTrace();
}
// Checking if the position was selected
if(selectedPos[position] == 1)
((ContactsHolder) holder).imgMerge.setVisibility(View.VISIBLE);
else
((ContactsHolder) holder).imgMerge.setVisibility(View.GONE);
}
I have resolved my issue here is the code if it could help someone:
#Override
public ContactsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_merge_contact, parent, false);
final ContactsHolder holder = new ContactsHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.getAdapterPosition() != RecyclerView.NO_POSITION) {
mSelectedItemPosition = holder.getAdapterPosition();
//notifyItemChanged(holder.getAdapterPosition());
notifyDataSetChanged();
}
}
});
return holder;
}
#Override
public void onBindViewHolder(ContactsHolder holder, int position) {
try {
if (mSelectedItemPosition == position) {
if (mergeFlag != 1) {
holder.imgMerge.setVisibility(View.VISIBLE);
mergeFlag = 1;
selectdParentId = contactsModels.get(position).alContactIdList;
} else{
//holder.relDone.setVisibility(View.GONE);
if (!selectdParentId.equals(contactsModels.get(position).alContactIdList)) {
holder.relDone.setVisibility(View.VISIBLE);
alChildId.add(contactsModels.get(position).alContactIdList);
} else {
holder.imgMerge.setVisibility(View.VISIBLE);
}
}
} else {
holder.imgMerge.setVisibility(View.GONE);
holder.relDone.setVisibility(View.GONE);
}
}
I use RecyclerView and I have implemented Search Filter on it and i am facing a problem here
After I search when I press on item I get wrong position not one I searched it please help me to solve this problem
For example item number 2 name "Android" after search "android" the position go number one .. why get this problem ? .. thank you
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public List<RecyclerItem> listItems;
private Context mContext;
public MyAdapter(List<RecyclerItem> listItems, Context mContext) {
this.listItems = listItems;
this.mContext = mContext;
}
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int position = holder.getAdapterPosition();
if (position == 0) {
Toast.makeText(mContext,"iOS",Toast.LENGTH_SHORT).show();
}
if (position == 1) {
Toast.makeText(mContext,"Android",Toast.LENGTH_SHORT).show();
}
}
});
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final RecyclerItem itemList = listItems.get(position);
holder.txtTitle.setText(itemList.getTitle());
holder.txtDescription.setText(itemList.getDescription());
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Display option menu
PopupMenu popupMenu = new PopupMenu(mContext, holder.txtOptionDigit);
popupMenu.inflate(R.menu.option_menu);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.mnu_item_save:
Toast.makeText(mContext, "Saved " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
break;
case R.id.mnu_item_delete:
//Delete item
Toast.makeText(mContext, "Deleted " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
listItems.remove(position);
notifyDataSetChanged();
break;
default:
break;
}
return false;
}
});
popupMenu.show();
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Button buttoncalling;
public TextView txtTitle;
public TextView txtDescription;
public TextView txtOptionDigit;
public ViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtDescription = (TextView) itemView.findViewById(R.id.txtDescription);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
buttoncalling = (Button) itemView.findViewById(R.id.bbbbbbbbbb);
buttoncalling.setOnClickListener(this);
}
#Override
public void onClick(View view) {
}
}
}
Filter
TextWatcher mTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().equals("")){
initAdapter();
} else {
searchItem(s.toString());
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
private void initAdapter(){
adapter.listItems.clear();
for (int i = 0; i < 10; i++) {
listItems.add(new RecyclerItem("Item " + (i + 1), "Welcome to Torisan channel, this is description of item " + (i+1)));
}
adapter.notifyDataSetChanged();
}
private void searchItem(String itemname){
int resultCount = 0;
adapter.listItems.clear();
for (int i = 0; i < tempListItems.size(); i++){
if (tempListItems.get(i).getTitle().contains(itemname)){
listItems.add(new RecyclerItem("Item " + (i + 1), "Welcome to Torisan channel, this is description of item " + (i+1)));
resultCount ++;
}
}
if (resultCount == 0){
showToast();
}
adapter.notifyDataSetChanged();
}
public void showToast() {
// Set the toast and duration
int toastDurationInMilliSeconds = 1000;
mToastToShow = Toast.makeText(this, "No results found.", Toast.LENGTH_LONG);
// Set the countdown to display the toast
CountDownTimer toastCountDown;
toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) {
public void onTick(long millisUntilFinished) {
mToastToShow.show();
}
public void onFinish() {
mToastToShow.cancel();
}
};
// Show the toast and starts the countdown
mToastToShow.show();
toastCountDown.start();
}
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public List<RecyclerItem> listItems;
private Context mContext;
public MyAdapter(List<RecyclerItem> listItems, Context mContext) {
this.listItems = listItems;
this.mContext = mContext;
}
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
view.setTag(getAdapterPosition());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int position = Integer.parse(v.getTag().toString());
if (position == 0) {
Toast.makeText(mContext,"iOS",Toast.LENGTH_SHORT).show();
}
if (position == 1) {
Toast.makeText(mContext,"Android",Toast.LENGTH_SHORT).show();
}
}
});
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final RecyclerItem itemList = listItems.get(position);
holder.txtTitle.setText(itemList.getTitle());
holder.txtDescription.setText(itemList.getDescription());
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Display option menu
PopupMenu popupMenu = new PopupMenu(mContext, holder.txtOptionDigit);
popupMenu.inflate(R.menu.option_menu);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.mnu_item_save:
Toast.makeText(mContext, "Saved " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
break;
case R.id.mnu_item_delete:
//Delete item
Toast.makeText(mContext, "Deleted " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
listItems.remove(position);
notifyDataSetChanged();
break;
default:
break;
}
return false;
}
});
popupMenu.show();
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Button buttoncalling;
public TextView txtTitle;
public TextView txtDescription;
public TextView txtOptionDigit;
public ViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtDescription = (TextView) itemView.findViewById(R.id.txtDescription);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
buttoncalling = (Button) itemView.findViewById(R.id.bbbbbbbbbb);
buttoncalling.setOnClickListener(this);
}
#Override
public void onClick(View view) {
}
}
}
Please use this
for (int i = 0; i < tempListItems.size(); i++) {
if (listItems.get(getAdapterPosition()).getName().equals(tempListItems.get(i).getName())) {
int selectedPos = i; //SelectedPos is that index
break;
}
}
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;
}
}