I'm creating a simple app that shows a list of item. Some of the item data is loaded in another thread, but when i scroll fast it shows the wrong data.
Here is the code for the adapter:
package com.lorenzorapetti.pokedex.adapter;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.lorenzorapetti.pokedex.R;
import com.lorenzorapetti.pokedex.Utils;
import com.lorenzorapetti.pokedex.model.PokemonSpecies;
import com.lorenzorapetti.pokedex.model.PokemonType;
import com.squareup.picasso.Picasso;
import org.apache.commons.lang3.StringUtils;
import java.lang.ref.WeakReference;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class PokemonSpeciesAdapter extends RecyclerView.Adapter<PokemonSpeciesAdapter.ViewHolder> {
private List<PokemonSpecies> mData;
private Context context;
public PokemonSpeciesAdapter(Context context, List<PokemonSpecies> data) {
this.context = context;
mData = data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView =((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.pokemon_species_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
PokemonSpecies item = mData.get(position);
holder.position = position;
Picasso.with(context)
.load(Utils.getSugimoriThumbUrl(item.getIdentifier()))
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(holder.image);
String identifier = "pokemon_species_" + Utils.convertIdentifier(item.getIdentifier())
+ "_name";
holder.textPrimary.setText(context.getResources().getString(
context.getResources().getIdentifier(identifier, "string", context.getPackageName())
));
holder.textSecondary.setText("#" + StringUtils.leftPad(item.getId().toString(), 3, "0"));
new AsyncLoad(item, holder, position).execute();
}
#Override
public int getItemCount() {
return mData != null ? mData.size() : 0;
}
#Override
public long getItemId(int position) {
return mData.get(position).getId();
}
public class ViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.pokemon_species_image) ImageView image;
#Bind(R.id.pokemon_species_name) TextView textPrimary;
#Bind(R.id.pokemon_species_number) TextView textSecondary;
#Bind(R.id.pokemon_species_primary_type)
TextView typePrimary;
#Bind(R.id.pokemon_species_secondary_type)
TextView typeSecondary;
int position;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
private class AsyncLoad extends AsyncTask<Void, Void, AsyncLoad.AsyncItem> {
private WeakReference<PokemonSpecies> itemData;
private WeakReference<ViewHolder> viewHolder;
private int mPosition;
public AsyncLoad(PokemonSpecies item, ViewHolder viewHolder, int position) {
this.itemData = new WeakReference<>(item);
this.viewHolder = new WeakReference<>(viewHolder);
mPosition = position;
}
#Override
protected AsyncLoad.AsyncItem doInBackground(Void... params) {
List<PokemonType> pokemonTypes = itemData.get().getDefaultPokemon().getPokemonTypes();
Log.d("App", "position: " + mPosition + ", holderPosition: " + viewHolder.get().position
+ ", pokemon: " + itemData.get().getIdentifier() + ", size: " + pokemonTypes.size());
String primaryIdentifier = "type_" +
Utils.convertIdentifier(pokemonTypes.get(0).getType().getIdentifier());
AsyncLoad.AsyncItem asyncItem = new AsyncLoad.AsyncItem();
asyncItem.primaryText = context.getResources().getString(
context.getResources().getIdentifier(primaryIdentifier + "_name", "string",
context.getPackageName()));
asyncItem.primaryColor = context.getResources().getColor(
context.getResources().getIdentifier(primaryIdentifier, "color",
context.getPackageName()));
if (pokemonTypes.size() == 2) {
String secondaryIdentifier = "type_" +
Utils.convertIdentifier(pokemonTypes.get(1).getType().getIdentifier());
asyncItem.secondaryText = context.getResources().getString(
context.getResources().getIdentifier(secondaryIdentifier + "_name", "string",
context.getPackageName()));
asyncItem.secondaryColor = context.getResources().getColor(
context.getResources().getIdentifier(secondaryIdentifier, "color",
context.getPackageName()));
}
return asyncItem;
}
#Override
protected void onPostExecute(AsyncLoad.AsyncItem asyncItem) {
ViewHolder holder = viewHolder.get();
if (mPosition == holder.position) {
holder.typePrimary.setText(asyncItem.primaryText);
holder.typePrimary.setBackgroundColor(asyncItem.primaryColor);
if (asyncItem.secondaryText != null) {
holder.typeSecondary.setText(asyncItem.secondaryText);
holder.typeSecondary.setBackgroundColor(asyncItem.secondaryColor);
}
}
}
protected class AsyncItem {
String primaryText;
int primaryColor;
String secondaryText;
int secondaryColor;
}
}
}
What can i do to load the exact data?
Related
As you can see in the picture I have two recycler Views (Parent and nested Recycler View), the parent recycler View is showing Semesters' list while the nested recycler View is showing subjects' list for that particular Semester. Now the problem is that I want to update the SGPA TextView (0.00) next to Semester TextView when a user enters credit hours and letter grade in particular Semester's subjects' list ... I am doing it by the following provided code, but it does not satisfy my needs...
Child Model Class
public class ChildModelClass {
String subject_LBL;
String credit_hours;
String letter_grade;
int delete_icon;
public ChildModelClass(String subject_LBL, int delete_icon, String credit_hours, String letter_grade) {
this.subject_LBL = subject_LBL;
this.delete_icon = delete_icon;
this.credit_hours = credit_hours;
this.letter_grade = letter_grade;
}
public String getSubject_LBL() {
return subject_LBL;
}
public String getCredit_hours() {
return credit_hours;
}
public void setCredit_hours(String credit_hours) {
this.credit_hours = credit_hours;
}
public String getLetter_grade() {
return letter_grade;
}
public void setLetter_grade(String letter_grade) {
this.letter_grade = letter_grade;
}
public void setSubject_LBL(String subject_LBL) {
this.subject_LBL = subject_LBL;
}
public int getDelete_icon() {
return delete_icon;
}
public void setDelete_icon(int delete_icon) {
this.delete_icon = delete_icon;
}
}
Child Adapter Class
import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
public class ChildAdapter extends RecyclerView.Adapter<ChildAdapter.ViewHolder> {
ArrayList<ChildModelClass> childModelClassList;
ArrayList<String> credit_hour_arrayList = new ArrayList<>();
// ArrayList<String> letter_grade_arrayList;
boolean isOnTextChanged = false;
int total_credit_hours = 0;
Context context;
TextView sGPA_value;
View rootView;
public ChildAdapter(ArrayList<ChildModelClass> childModelClassList,Context context) {
this.childModelClassList = childModelClassList;
this.context = context;
}
#NonNull
#Override
public ChildAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View v =layoutInflater.inflate(R.layout.child_rv_layout,parent,false);
context = parent.getContext();
rootView = ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content);
sGPA_value = rootView.findViewById(R.id.semester_gpa_value);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ChildAdapter.ViewHolder holder, int position) {
ChildModelClass list = childModelClassList.get(position);
holder.TIET_credit_hour.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
isOnTextChanged = true;
// list.credit_hours = charSequence.toString();
}
#Override
public void afterTextChanged(Editable editable) {
total_credit_hours = 0;
if (isOnTextChanged) {
isOnTextChanged = false;
try {
for (int i = 0; i <= holder.getAdapterPosition(); i++) {
if (i != holder.getAdapterPosition()) {
credit_hour_arrayList.add("0");
}else {
credit_hour_arrayList.add("0");
credit_hour_arrayList.set(holder.getAdapterPosition(),editable.toString());
break;
}
}
for (int i = 0; i <= credit_hour_arrayList.size() -1; i++) {
int tempTotalCreditHours = Integer.parseInt(credit_hour_arrayList.get(i));
total_credit_hours = total_credit_hours + tempTotalCreditHours;
}
// total_final_credit_hours = String.valueOf(total_credit_hours);
sGPA_value.setText(String.valueOf(total_credit_hours));
}catch (NumberFormatException e) {
total_credit_hours = 0;
for (int i = 0; i <= holder.getAdapterPosition(); i++) {
int newPosition = holder.getAdapterPosition();
if (i == newPosition) {
credit_hour_arrayList.set(newPosition,"0");
}
}
for (int i = 0; i < credit_hour_arrayList.size()-1; i++) {
int tempTotalCreditHours = Integer.parseInt(credit_hour_arrayList.get(i));
total_credit_hours = total_credit_hours + tempTotalCreditHours;
}
// total_final_credit_hours = String.valueOf(total_credit_hours);
sGPA_value.setText(String.valueOf(total_credit_hours));
}
}
}
});
holder.subject_LBL.setText(list.getSubject_LBL());
holder.delete_icon.setImageResource(list.getDelete_icon());
holder.TIET_credit_hour.setText(list.getCredit_hours());
holder.TIET_letter_grade.setText(list.getLetter_grade());
}
#Override
public int getItemCount() {
return childModelClassList.size();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
ConstraintLayout child_rv_layout, card_view_layout;
MaterialCardView card_view;
TextView subject_LBL;
ImageView delete_icon;
TextInputLayout TIL_credit_hour, TIL_letter_grade;
TextInputEditText TIET_credit_hour, TIET_letter_grade;
public ViewHolder(#NonNull View itemView) {
super(itemView);
child_rv_layout = itemView.findViewById(R.id.child_rv_layout);
card_view_layout = itemView.findViewById(R.id.card_view_layout);
card_view = itemView.findViewById(R.id.card_view);
subject_LBL = itemView.findViewById(R.id.subject_LBL);
delete_icon = itemView.findViewById(R.id.delete_icon);
TIL_credit_hour = itemView.findViewById(R.id.TIL_credit_hour);
TIL_letter_grade = itemView.findViewById(R.id.TIL_letter_grade);
TIET_credit_hour = itemView.findViewById(R.id.TIET_credit_hour);
TIET_letter_grade = itemView.findViewById(R.id.TIET_letter_grade);
delete_icon.setOnClickListener(view -> {
childModelClassList.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
});
}
}
}
Parent Model Class
import java.util.ArrayList;
public class ParentModelClass {
String semester_LBL;
String semester_GPA_value;
ArrayList<ChildModelClass> childModelClassList;
public ParentModelClass(String semester_LBL, String semester_GPA_value, ArrayList<ChildModelClass> childModelClassList) {
this.semester_LBL = semester_LBL;
this.semester_GPA_value = semester_GPA_value;
this.childModelClassList = childModelClassList;
}
public String getSemester_LBL() {
return semester_LBL;
}
public void setSemester_LBL(String semester_LBL) {
this.semester_LBL = semester_LBL;
}
public String getSemester_GPA_value() {
return semester_GPA_value;
}
public void setSemester_GPA_value(String semester_GPA_value) {
this.semester_GPA_value = semester_GPA_value;
}
}
Parent Adapter Class
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ParentAdapterClass extends RecyclerView.Adapter<ParentAdapterClass.ViewHolder> {
ArrayList<ParentModelClass> parentModelClassArrayList;
Context context;
public ParentAdapterClass(ArrayList<ParentModelClass> parentModelClassArrayList, Context context) {
this.parentModelClassArrayList = parentModelClassArrayList;
this.context = context;
}
#NonNull
#Override
public ParentAdapterClass.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View v =layoutInflater.inflate(R.layout.parent_rv_layout,parent,false);
return new ViewHolder(v);
}
#SuppressLint("NotifyDataSetChanged")
#Override
public void onBindViewHolder(#NonNull ParentAdapterClass.ViewHolder holder, int position) {
ParentModelClass list = parentModelClassArrayList.get(position);
holder.semester_LBL.setText(list.getSemester_LBL());
holder.semester_gpa_value.setText(list.getSemester_GPA_value());
ChildAdapter childAdapter;
childAdapter = new ChildAdapter(parentModelClassArrayList.get(position).childModelClassList, context);
ListDecorator listDecorator = new ListDecorator(0,15,15,0);
holder.child_rv.addItemDecoration(listDecorator);
holder.child_rv.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
holder.child_rv.setAdapter(childAdapter);
holder.child_rv.setHasFixedSize(true);
childAdapter.notifyDataSetChanged();
}
#Override
public int getItemCount() {
return parentModelClassArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ConstraintLayout parent_rv_layout, semester_gpa_display_layout;
RecyclerView child_rv;
TextView semester_LBL, semester_gpa_value;
public ViewHolder(#NonNull View itemView) {
super(itemView);
parent_rv_layout = itemView.findViewById(R.id.parent_rv_layout);
semester_gpa_display_layout = itemView.findViewById(R.id.semester_gpa_display_layout);
child_rv = itemView.findViewById(R.id.child_rv);
semester_LBL = itemView.findViewById(R.id.semester_LBL);
semester_gpa_value = itemView.findViewById(R.id.semester_gpa_value);
}
}
}
MainActivity
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ConstraintLayout parent_layout, CGPA_display_layout;
TextView Label_CGPA, CGPA_value;
RecyclerView parent_rv;
ArrayList<ParentModelClass> parentModelClassArrayList;
ArrayList<ChildModelClass> childModelClassArrayList;
ArrayList<ChildModelClass> semester_1;
ArrayList<ChildModelClass> semester_2;
ArrayList<ChildModelClass> semester_3;
ArrayList<ChildModelClass> semester_4;
#SuppressLint("NotifyDataSetChanged")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parent_layout = findViewById(R.id.parent_layout);
CGPA_display_layout = findViewById(R.id.CGPA_display_layout);
Label_CGPA = findViewById(R.id.Label_CGPA);
CGPA_value = findViewById(R.id.CGPA_value);
parent_rv = findViewById(R.id.parent_rv);
childModelClassArrayList = new ArrayList<>();
semester_1 = new ArrayList<>();
semester_2 = new ArrayList<>();
semester_3 = new ArrayList<>();
semester_4 = new ArrayList<>();
parentModelClassArrayList = new ArrayList<>();
ParentAdapterClass parentAdapterClass;
semester_1.add(new ChildModelClass("Subject 1", R.drawable.ic_delete, "", ""));
semester_1.add(new ChildModelClass("Subject 2", R.drawable.ic_delete, "", ""));
semester_1.add(new ChildModelClass("Subject 3", R.drawable.ic_delete, "", ""));
semester_1.add(new ChildModelClass("Subject 4", R.drawable.ic_delete, "", ""));
semester_2.add(new ChildModelClass("Subject 1", R.drawable.ic_delete, "", ""));
semester_2.add(new ChildModelClass("Subject 2", R.drawable.ic_delete, "", ""));
semester_2.add(new ChildModelClass("Subject 3", R.drawable.ic_delete, "", ""));
semester_2.add(new ChildModelClass("Subject 4", R.drawable.ic_delete, "", ""));
semester_3.add(new ChildModelClass("Subject 1", R.drawable.ic_delete, "", ""));
semester_3.add(new ChildModelClass("Subject 2", R.drawable.ic_delete, "", ""));
semester_3.add(new ChildModelClass("Subject 3", R.drawable.ic_delete, "", ""));
semester_3.add(new ChildModelClass("Subject 4", R.drawable.ic_delete, "", ""));
semester_4.add(new ChildModelClass("Subject 1", R.drawable.ic_delete, "", ""));
semester_4.add(new ChildModelClass("Subject 2", R.drawable.ic_delete, "", ""));
semester_4.add(new ChildModelClass("Subject 3", R.drawable.ic_delete, "", ""));
semester_4.add(new ChildModelClass("Subject 4", R.drawable.ic_delete, "", ""));
parentModelClassArrayList.add(new ParentModelClass("Semester 1", "0.00", semester_1));
parentModelClassArrayList.add(new ParentModelClass("Semester 2", "0.00", semester_2));
parentModelClassArrayList.add(new ParentModelClass("Semester 3", "0.00", semester_3));
parentModelClassArrayList.add(new ParentModelClass("Semester 4", "0.00", semester_4));
parentAdapterClass = new ParentAdapterClass(parentModelClassArrayList,MainActivity.this);
ListDecorator listDecorator = new ListDecorator(20, 0,0, 20);
parent_rv.addItemDecoration(listDecorator);
parent_rv.setAdapter(parentAdapterClass);
parent_rv.setHasFixedSize(true);
parent_rv.setLayoutManager(new LinearLayoutManager(this));
parentAdapterClass.notifyDataSetChanged();
}
}
If I understood your question correctly, you want to update the parent textView adapter from child adapter.
You are using this line of code:
rootView = ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content);
to be able to access textview (semester_gpa_value) from the child adapter.
There is a better way to achieve this using the Observer pattern, just send the text from the child adapter to the parent adapter. this way you will be able to update semester_gpa_value from parent adapter, so you don't need to access it in child adapter.
So make these changes in the child adapter:
public class ChildAdapter extends RecyclerView.Adapter<ChildAdapter.ChildViewHolder> {
//...
public interface ValueChangeListener {
void onValueChange(String newValue);
}
private ValueChangeListener valueChangeListener;
//...
class ChildViewHolder extends RecyclerView.ViewHolder {
EditText TIET_credit_hour;
public ChildViewHolder(#NonNull View itemView) {
super(itemView);
//...
TIET_credit_hour = itemView.findViewById(R.id.TIET_credit_hour);
TIET_credit_hour.addTextChangedListener(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) {}
#Override
public void afterTextChanged(Editable s) {
if (valueChangeListener != null) {
// In this case, I just send the text as is to the parent adapter, but you can do whatever calculations you want before sending it.
valueChangeListener.onValueChange(s.toString());
}
}
});
}
}
// this method must be called by parent adapter to listen for text change
public void setValueChangeListener(ValueChangeListener valueChangeListener) {
this.valueChangeListener = valueChangeListener;
}
}
In your parent adapter, just call childAdapter.setValueChangeListener(yourText) to be able to receive the text sent by the child adapter:
ParentAdapter.java:
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
//...
childAdapter.setValueChangeListener(new ChildAdapter.ValueChangeListener() {
#Override
public void onValueChange(String newValue) {
//Also here you can do any calculation you want before updating the text view. In this example I just show the text received from the child adapter.
holder.semester_gpa_value.setText(newValue);
}
});
}
As you can see, we are updating the text view of the parent adapter with the text received from the child adapter.
I am creating a document arrangement activity with RecyclerView. I want to arrange the document with drag and drop. It was done by using ItemTouchHelper.Callbackbut after that I can't set the page number after the OnItemMove callback. what should I do?
EDIT: added code snippet
package adapters;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.pdf.PdfRenderer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.mobilix.docscanner.R;
import java.util.ArrayList;
import java.util.Collections;
import helper.ItemTouchHelperAdapter;
import helper.ItemTouchHelperViewHolder;
import helper.OnStartDragListener;
import helper.SimpleItemTouchHelperCallback;
public class PageAjdustAdapter extends RecyclerView.Adapter<PageAjdustAdapter.PageAdjustHolder> implements ItemTouchHelperAdapter, OnStartDragListener {
private final String TAG = getClass().getName();
Context mContext;
ArrayList<PdfPage> pdfPages = new ArrayList<>();
private ItemTouchHelper itemTouchHelper;
public PageAjdustAdapter(Context context, ArrayList<PdfPage> pages) {
this.mContext = context;
pdfPages = pages;
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(this);
itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(((Activity) context).findViewById(R.id.rcvPageArrange));
}
#NonNull
#Override
public PageAdjustHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_page_adajustment, parent, false);
return new PageAdjustHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PageAdjustHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: ");
holder.ivPage.setImageBitmap(pdfPages.get(position).bitmap);
holder.cbPage.setChecked(pdfPages.get(position).isSelected);
holder.tvPageNo.setText(String.valueOf(position + 1));
holder.cbPage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
pdfPages.get(holder.getAdapterPosition()).isSelected = isChecked;
}
});
holder.ivRotate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getAdapterPosition();
pdfPages.get(pos).bitmap = Bitmap.createBitmap(//
pdfPages.get(pos).bitmap, 0, 0, pdfPages.get(pos).bitmap.getWidth(),//
pdfPages.get(pos).bitmap.getHeight(), pdfPages.get(pos).matrix, true);//
notifyItemChanged(pos);
}
});
}
#Override
public int getItemCount() {
return pdfPages.size();
}
#Override
public boolean onItemMove(int fromPosition, int toPosition) {
Log.d(TAG, "onItemMove: ->fp " + (fromPosition + 1) + " tp-> " + (toPosition + 1));
Collections.swap(pdfPages, fromPosition, toPosition);
notifyItemMoved(fromPosition, toPosition);
return false;
}
#Override
public void onItemDismiss(int position) {
pdfPages.remove(position);
notifyItemRemoved(position);
}
#Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
itemTouchHelper.startDrag(viewHolder);
}
public static class PageAdjustHolder extends RecyclerView.ViewHolder implements
ItemTouchHelperViewHolder {
ImageView ivPage, ivRotate;
CheckBox cbPage;
TextView tvPageNo;
public PageAdjustHolder(#NonNull View itemView) {
super(itemView);
ivPage = itemView.findViewById(R.id.ivPage);
ivRotate = itemView.findViewById(R.id.ivRotate);
cbPage = itemView.findViewById(R.id.cbPage);
tvPageNo = itemView.findViewById(R.id.tvPageNo);
}
#Override
public void onItemSelected() {
}
#Override
public void onItemClear() {
}
}
public static class PdfPage {
PdfRenderer.Page page;
Bitmap bitmap;
boolean isSelected;
Matrix matrix;
int rotate = 0;
public PdfPage(PdfRenderer.Page page, Bitmap bitmap) {
this.page = page;
this.bitmap = bitmap;
matrix = new Matrix();
rotate += 90;
matrix.postRotate(90);//martix work on +=90
}
}
}
You have to call notifyDataSetChanged() when an item position is changed. The easiest way it to used onItemClear(), it will be called when an item is de-selected. Add it like following.
#Override
public void onItemClear() {
notifyDataSetChanged();
}
One thing you have to add is check weather the position is actually changed after the drag operation or not other wise it will always update the whole dataset whenever an item is selected and than de-selected.
Edit
Create a local variable in view-holder class. Than you just have to set it in onItemSelected() and check it in onItemClear();
#Override
public void onItemSelected() {
lastpos = getAdapterPosition();
}
#Override
public void onItemClear() {
if(lastpos != getAdapterPosition())
notifyDataSetChanged();
}
I'm having this issue where the old viewHolder of a position in the recyclerview isn't deleted or reset before recycling it. In my case this means that if I scroll and go back to the former position it now has two views stacked on top of each other. I tried solving this by setting the visiblity of the view to be inflated to gone but this is a solution for the short run and I want to understand how to really solve this. I also tried to setRecycble(false) but then my views take longer to inflate and recycling the views also makes more sense My Adapter code is below:
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.chatr.app.android.Interfaces.MessageListParent;
import com.chatr.app.android.Models.ChatrInvitePending;
import com.chatr.app.android.Models.ChatrMessagingInfo;
import com.chatr.app.android.R;
import com.chatr.app.android.Repositories.MessageRepository;
import com.chatr.app.android.RoomDB.ChatDatabase.ChatEntity;
import com.chatr.app.android.RoomDB.MessagesDatabase.MessageEntity;
import com.chatr.app.android.Tools.ChatrApplication;
import com.chatr.app.android.Tools.ChatrErrorHandler;
import com.chatr.app.android.Views.MessageItemView;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.chatr.app.android.Manager.MessageManager.CONSTANT_OTHER_TYPE;
import static com.chatr.app.android.Manager.MessageManager.CONSTANT_SELF_TYPE;
public class MessageListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//Constants
private static final String TAG = "MessageListAdapter";
private static final int CONSTANT_MESSAGE_TYPE = 0;
private static final int CONSTANT_INFORMATION_TYPE = 1;
//Data list
private final ArrayList<MessageEntity> messageEntityList = new ArrayList<>();
private final ArrayList<Object> additionalInformationList = new ArrayList<>();
//Callback
private final MessageListParent parentCallback;
public MessageListAdapter(MessageListParent parent) {
this.parentCallback = parent;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
if (viewType == CONSTANT_MESSAGE_TYPE) {
MessageItemView messageItemView = new MessageItemView(parent.getContext());
messageItemView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
viewHolder = new MessageViewHolder(messageItemView);
}
else if(viewType == CONSTANT_INFORMATION_TYPE){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_chat_view_information_text,parent);
//v.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
viewHolder = new InformationTextViewHolder(v);
}
return viewHolder;
}
#Override
public int getItemViewType(int position) {
Object v = null;
for(Object obj : additionalInformationList){
if (additionalInformationList.get(position) instanceof ChatrInvitePending){
if (((ChatrInvitePending)
additionalInformationList.get(position)).getRecyclerViewPosition() == position){
v = obj;
break;
}
}
else if (additionalInformationList.get(position) instanceof ChatrMessagingInfo){
if (((ChatrMessagingInfo)
additionalInformationList.get(position)).getRecyclerViewPosition() == position){
v = obj;
break;
}
}
}
if (v == null){
return CONSTANT_MESSAGE_TYPE;
}
else{
return CONSTANT_INFORMATION_TYPE;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()){
case CONSTANT_MESSAGE_TYPE:
generateMessageTypeView((MessageViewHolder) holder, position);
case CONSTANT_INFORMATION_TYPE:
//generateInformationTypeView((InformationTextViewHolder) holder, position);
}
}
public void generateMessageTypeView(MessageViewHolder holder, int position) {
try{
holder.messageItemView.setFormerEntity(messageEntityList.get(position-1));
}catch (Exception e){
ChatrErrorHandler.handleException(e);
}
holder.messageItemView.setEntity(messageEntityList.get(position));
if(!messageEntityList.get(position).isRead()) {
parentCallback.viewIsRead(messageEntityList.get(position));
}
}
#Override
public int getItemCount() {
return messageEntityList.size();
}
public void updateMessageList(List<MessageEntity> messageEntitiesList) {
this.messageEntityList.clear();
this.messageEntityList.addAll(new ArrayList<>(messageEntitiesList));
notifyItemInserted(messageEntitiesList.size());
}
public void updateAdditionalInfoList(List<Object> additionalList) {
this.additionalInformationList.clear();
this.additionalInformationList.addAll(new ArrayList<>(additionalList));
notifyItemInserted(additionalList.size());
}
#Override
public void onViewRecycled(#NonNull #NotNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
MessageViewHolder messageViewHolder = (MessageViewHolder) holder;
messageViewHolder.messageItemView.clear();
}
public static class MessageViewHolder extends RecyclerView.ViewHolder{
private final MessageItemView messageItemView;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
messageItemView = (MessageItemView) itemView;
}
}
public static class InformationTextViewHolder extends RecyclerView.ViewHolder{
private final TextView textView;
public InformationTextViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.title_information_text_chat);
}
}
}
Here you can see the issue I have:
Here is my view that I inflate:
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.chatr.app.android.Manager.MediaManager;
import com.chatr.app.android.Manager.MessageManager;
import com.chatr.app.android.R;
import com.chatr.app.android.Repositories.ChatRepository;
import com.chatr.app.android.Repositories.MessageRepository;
import com.chatr.app.android.RoomDB.ChatDatabase.ChatEntity;
import com.chatr.app.android.RoomDB.MediaDatabase.MediaEntity;
import com.chatr.app.android.RoomDB.MessagesDatabase.MessageEntity;
import org.jetbrains.annotations.NotNull;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MessageItemView extends FrameLayout {
private static final long CONSTANT_TIME_5_MIN = 300000;
private int viewType = 1;
private MessageEntity messageEntity;
private TextView txtContent;
private TextView txtTime;
private ImageView imageView;
private AudioMessageView audioMessageView;
private ChatrGradientView chatrGradientView;
private final String regexEmoji = "([\\u20a0-\\u32ff\\ud83c\\udc00-\\ud83d\\udeff\\udbb9\\udce5-\\udbb9\\udcee])";
private static final String TAG = "MessageItemView";
private MessageEntity formerMessageEntity;
public MessageItemView(#NonNull Context context) {
super(context);
}
public MessageItemView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public MessageItemView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MessageItemView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
private void init() {
Log.d(TAG, "init: " + viewType);
if (viewType == MessageManager.CONSTANT_OTHER_TYPE) {
Log.d(TAG, "init:3 ");
LayoutInflater.from(getContext()).inflate(R.layout.layout_chat_other_message_view_item, this);
}
if (viewType == MessageManager.CONSTANT_SELF_TYPE) {
Log.d(TAG, "ini2t: " + viewType);
LayoutInflater.from(getContext()).inflate(R.layout.layout_chat_self_message_view_item, this);
}
initViews();
}
#NotNull
public String convertMillisToTime(long millis) {
Log.d(TAG, "convertMillisToTime: " + millis);
DateFormat formatter = new SimpleDateFormat("HH:mm", Locale.GERMANY);
formatter.setTimeZone(TimeZone.getTimeZone("GMT+2" +
""));
return formatter.format(new Date(millis*1000));
}
private void initViews() {
Log.d(TAG, "initViews: ");
imageView = findViewById(R.id.img_content_message_item);
txtContent = findViewById(R.id.txt_content_message_item);
txtTime = findViewById(R.id.message_date_indicator_txt);
chatrGradientView = findViewById(R.id.img_message_item_profile_pic);
audioMessageView = findViewById(R.id.audio_message_view_in_message);
ChatRepository.get(getContext())
.getStartGradientChatEntity(messageEntity.getChatId(), new ChatRepository.GetGradient() {
#Override
public void getGradient(int color) {
chatrGradientView.setGradientStartColor(color);
}
});
ChatRepository.get(getContext())
.getEndGradientChatEntity(messageEntity.getChatId(), new ChatRepository.GetGradient() {
#Override
public void getGradient(int color) {
chatrGradientView.setGradientEndColor(color);
}
});
imageView.setVisibility(GONE);
txtContent.setVisibility(VISIBLE);
if (formerMessageEntity == null || formerMessageEntity.getDateSent() > CONSTANT_TIME_5_MIN ){
txtTime.setVisibility(VISIBLE);
txtTime.setText(convertMillisToTime(messageEntity.getDateSent()));
}
if (messageEntity != null) {
imageView.setVisibility(GONE);
txtContent.setVisibility(VISIBLE);
txtContent.setText(messageEntity.getContentText());
}
Log.d(TAG, "run-3: ");
if (messageEntity.getMediaId()!= -1){
txtContent.setVisibility(GONE);
Log.d(TAG, "run-2: " + messageEntity.getMediaId());
MessageRepository.get(getContext()).getMediaWithId(messageEntity.getMediaId(),
new MessageRepository.getMediaEntity() {
#Override
public void getMedia(MediaEntity mediaEntity) {
Log.d(TAG, "run-1: " + mediaEntity);
mediaAvailabilityWork(mediaEntity);
}
});
}
else{
Glide.with(MessageItemView.this).clear(imageView);
imageView.setImageDrawable(null);
imageView.setVisibility(GONE);
}
Matcher matchEmo = Pattern.compile(regexEmoji).matcher(txtContent.getText());
while(matchEmo.find()){
Log.d(TAG, "initViews: ");
Spannable spannable = new SpannableString(txtContent.getText());
spannable.setSpan(new ForegroundColorSpan(Color.WHITE), matchEmo.start(),
matchEmo.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
txtContent.setText(spannable, TextView.BufferType.SPANNABLE);
}
}
public void mediaAvailabilityWork(MediaEntity mediaEntity) {
Log.d(TAG, "run0: ");
if (mediaEntity != null) {
Log.d(TAG, "run1: " +mediaEntity.getTypeMedia());
if (mediaEntity.getTypeMedia().equals(MediaManager.CONSTANT_MEDIA_TYPE_AUDIO)){
audioMessageView.post(new Runnable(){
#Override
public void run() {
Log.d(TAG, "run2: ");
audioMessageView.setVisibility(VISIBLE);
imageView.setVisibility(GONE);
audioMessageView.setMediaEntity(mediaEntity);
}
});
}
else if (mediaEntity.getTypeMedia().equals(MediaManager.CONSTANT_MEDIA_TYPE_IMG)){
imageView.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "run3123123: ");
imageView.setVisibility(VISIBLE);
audioMessageView.setVisibility(GONE);
Glide.with(MessageItemView.this).
load(mediaEntity.getFileUrl()).centerCrop().into(imageView);
}
});
}
}
}
public void setEntity(MessageEntity messageEntity) {
this.viewType = messageEntity.getChatType();
this.messageEntity = messageEntity;
Log.d(TAG, "setEntity: " + messageEntity.getMediaId());
init();
}
public void setFormerEntity(MessageEntity formerMessageEntity) {
this.formerMessageEntity = formerMessageEntity;
}
public void clear() {
viewType = 1;
txtTime.setText("");
txtContent.setText("");
audioMessageView.setVisibility(GONE);
txtContent.setVisibility(GONE);
this.postInvalidate();
}
}
I Have problem to change background color of GroupView on position..
According to My Code
when i press 1nd number GroupView then the color change of 1st number GroupView.
AND
when i press 2nd number GroupView then 1st number GroupView is color is Changed.
I Want to change GroupView Color on Postion Expand and Collapse.
ExpandableListViewAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.NumberPicker;
import android.widget.TextView;
import com.acase.clouds.cloudstailor.Models.ExpandableModel;
import com.acase.clouds.cloudstailor.R;
import java.util.List;
public class ExpandableListViewAdapter extends BaseExpandableListAdapter {
private Context context;
private LayoutInflater inflater;
private List<ExpandableModel> listDataGroup;
public ExpandableListViewAdapter(Context context, List<ExpandableModel> listDataGroup) {
this.context = context;
this.listDataGroup = listDataGroup;
this.inflater = LayoutInflater.from(context);
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return listDataGroup.get(groupPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 1;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ExpandableModel model = listDataGroup.get(groupPosition);
if (convertView == null) {
convertView = inflater.inflate(model.getLayoutId(), null);
}
switch (model.getType()) {
case AGE:
setNumberPicker(convertView, model);
break;
case STATE:
setNumberPicker(convertView, model);
break;
}
return convertView;
}
private void setNumberPicker(View convertView, final ExpandableModel model) {
NumberPicker numberPicker = convertView.findViewById(R.id.numberPicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(99);
if (!model.getValue().isEmpty()) {
numberPicker.setValue(Integer.parseInt(model.getValue()));
}
// to change formate of number in numberpicker
numberPicker.setFormatter(new NumberPicker.Formatter() {
#Override
public String format(int i) {
return String.format("%02d", i);
}
});
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
model.setValue(i1 + "");
}
});
}
#Override
public int getChildrenCount(int groupPosition) {
return 1;
}
#Override
public Object getGroup(int groupPosition) {
return this.listDataGroup.get(groupPosition);
}
#Override
public int getGroupCount() {
return this.listDataGroup.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row_group, null);
}
ExpandableModel model = listDataGroup.get(groupPosition);
TextView tv_title = convertView.findViewById(R.id.tv_title);
TextView tv_value = convertView.findViewById(R.id.tv_value);
tv_title.setText(model.getName());
tv_value.setText(model.getValue());
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
EditProfileActivity
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.acase.clouds.cloudstailor.Adapter.ExpandableListViewAdapter;
import com.acase.clouds.cloudstailor.Models.ExpandableModel;
import com.bumptech.glide.Glide;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class EditProfileActivity extends AppCompatActivity {
Toolbar toolbar;
ImageView profileimage;
TextView changephototext, textView;
RelativeLayout item;
private static final int PICK_IMAGE_REQUEST = 1;
public Uri path;
private ExpandableListView expandableListView;
private ExpandableListViewAdapter expandableListViewAdapter;
List<ExpandableModel> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
toolbar = findViewById(R.id.tool).findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Edit Profile");
profileimage = findViewById(R.id.Profile_Img);
profileimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fileChooser();
}
});
changephototext = findViewById(R.id.Change_Photo_Button);
changephototext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fileChooser();
}
});
// initializing the views
initViews();
// initializing the listeners
initListeners();
// initializing the objects
initObjects();
}
private void initViews() {
expandableListView = findViewById(R.id.expandableListView);
}
private void initListeners() {
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
ExpandableModel model = list.get(groupPosition);
Toast.makeText(EditProfileActivity.this, model.getName() + " clicked at " + childPosition, Toast.LENGTH_SHORT).show();
return false;
}
});
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
ExpandableModel model = list.get(groupPosition);
Toast.makeText(EditProfileActivity.this, model.getName() + " expanded", Toast.LENGTH_SHORT).show();
item = findViewById(R.id.Group);
item.setBackgroundResource(R.drawable.selectedlistback);
textView = findViewById(R.id.tv_title);
textView.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
}
});
// ExpandableListView Group collapsed listener
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
ExpandableModel model = list.get(groupPosition);
Toast.makeText(EditProfileActivity.this, model.getName() + " collapsed", Toast.LENGTH_SHORT).show();
item = findViewById(R.id.Group);
item.setBackgroundResource(R.drawable.listback);
textView = findViewById(R.id.tv_title);
textView.setTextColor(getResources().getColor(R.color.colorAccent));
}
});
}
private void initObjects() {
ExpandableModel age = new ExpandableModel("AGE", "", ExpandableModel.ExpandableType.AGE, R.layout.list_row_child);
list.add(age);
ExpandableModel state = new ExpandableModel("STATE", "", ExpandableModel.ExpandableType.STATE, R.layout.list_row_child);
list.add(state);
expandableListViewAdapter = new ExpandableListViewAdapter(this, list);
expandableListView.setAdapter(expandableListViewAdapter);
}
private void fileChooser()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data.getData() != null)
{
path = data.getData();
Glide.with(this).load(path).into(profileimage);
path = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),path);
profileimage.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}
}
}
Try add the following code inside getGroupView of your adapter:
if(isExpanded) {
convertView.setBackgroundResource(R.drawable.selectedlistback);
tv_title.setTextColor(context.getResources().getColor(R.color.colorPrimaryDark));
}else{
convertView.setBackgroundResource(R.drawable.listback);
tv_title.setTextColor(context.getResources().getColor(R.color.colorAccent));
}
and remove the listeners. Hope that helps!
My code was worked perfectly just before i added header image, after that listview not showing the given datas.
These are the main pages.
Can anyone help please.Any help will be appreciated.
MyRecyclerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MyRecyclerViewAdapter extends
RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
Context context;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
String[] data;
public MyRecyclerViewAdapter(String[] data) {
this.data = data;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView desc;
ImageView image,head_img;
public DataObjectHolder(View itemView) {
super(itemView);
desc = (TextView) itemView.findViewById(R.id.description);
image = (ImageView) itemView.findViewById(R.id.image);
head_img=(ImageView) itemView.findViewById(R.id.header_img);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
this.mDataset = myDataset;
this.context=context;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType==TYPE_ITEM) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview, parent, false);
//DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return new DataObjectHolder(view);
}
else if (viewType==TYPE_HEADER){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
//DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return new DataObjectHolder(view);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
if(holder instanceof VHItem) {
holder.desc.setText(mDataset.get(position ).getDescription());
// holder.image.setText(mDataset.get(position).getImage_url());
Picasso.with(holder.image.getContext()).load(mDataset.get(position ).getImage_url()).into(holder.image);
}
else if(holder instanceof VHHeader){
holder.head_img.setImageResource(R.drawable.cam);
}
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return (null != mDataset ? mDataset.size() + 1 : 0);
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
private class VHItem extends DataObjectHolder {
public VHItem(View itemView) {
super(itemView);
}
}
private class VHHeader extends DataObjectHolder {
public VHHeader(View itemView) {
super(itemView);
}
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
private String getItem(int position) {
return data[position - 1];
}
}
Profile2Fragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class Profile2Fragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.recycler_view, container, false);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
return rootview;
}
private ArrayList<DataObject> getDataSet() {
ArrayList<DataObject> results = new ArrayList<DataObject>();
for (int index = 0; index < 1; index++) {
DataObject obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "https://mediastream.jumeirah.com/webimage/heroactual//globalassets/global/hotels-and-resorts/dubai/madinat-jumeirah/restaurants/pierchic/madinat-jumeirah-pierchic-inside-restaurant-02-hero.jpg");
results.add(obj);
obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "https://photos.smugmug.com/Portfolio/i-HBk894k/0/db7f0344/L/The%20Black%20Couches-L.jpg");
results.add(obj);
obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "http://thesmartlocal.com/images/easyblog_images/82/Pollen.jpg");
results.add(obj);
}
return results;
}
}
DataObject.java
public class DataObject {
private String description;
private String image_url;
DataObject (String text1, String text2){
description = text1;
image_url = text2;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
try to change return statement
`return new DataObjectHolder(view);
to your specific Class like return
new VHHeader(view);
and
return new VHItem(view);
in onCreateViewHolder..