Android recyclerview content changes onscroll - android

I'm using RecyclerView to display a list, and each item in RecyclerView is shown as a CardView. When RecyclerView is scrolled down the content inside CardView changes.
Before scrolling down:
After scrolling down:
As you can see in above two images "UNKNOWN" was changed to "null". The contents shown inside RecyclerView is fetched from SQLite. Could not find any solution after hours and hours of googling.
Adapter Class:
public class DraftListAdapter extends
RecyclerView.Adapter<DraftListAdapter.ViewHolder> {
private static final String TAG = "DraftListAdapter";
private ArrayList<EventDAO> al_item_list;
private int rowLayout;
private Activity obj_activity;
private DisplayImageOptions obj_display_image_options;
private static RecyclerViewClickListener itemListener;
private SimpleDateFormat obj_date_formater_display = new SimpleDateFormat(
"MMMM d, yyyy");
private SimpleDateFormat obj_date_formater_sqlite = new SimpleDateFormat(
"yyyy-MM-dd");
public DraftListAdapter(ArrayList<EventDAO> al_item_list, int rowLayout,
Activity obj_activity, DisplayImageOptions obj_display_image_options) {
this.al_item_list = al_item_list;
this.rowLayout = rowLayout;
this.obj_activity = obj_activity;
this.obj_display_image_options = obj_display_image_options;
}
public DraftListAdapter(ArrayList<EventDAO> al_item_list, int rowLayout,
Activity obj_activity,
DisplayImageOptions obj_display_image_options,
RecyclerViewClickListener itemListener) {
this.al_item_list = al_item_list;
this.rowLayout = rowLayout;
this.obj_activity = obj_activity;
this.obj_display_image_options = obj_display_image_options;
this.itemListener = itemListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout,
viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
final EventDAO obj_current = al_item_list.get(position);
viewHolder.button_edit.setText("EDIT");
viewHolder.imageview_bookmark.setVisibility(View.INVISIBLE);
viewHolder.imageview_call.setVisibility(View.INVISIBLE);
//display event banner
viewHolder.imageview_event_banner.setTag(position);
viewHolder.textview_event_name.setTag(position);
ImageLoader.getInstance().displayImage("file:///"+obj_current.eventBanner,
viewHolder.imageview_event_banner, obj_display_image_options,null);
viewHolder.imageview_event_banner.setAlpha(200);
//display event location slug
viewHolder.textview_event_name.setText(obj_current.eventName);
if (obj_current.isOnline.equals("1")) {
viewHolder.linearlayout_location.setVisibility(View.GONE);
viewHolder.linearlayout_online.setVisibility(View.VISIBLE);
viewHolder.textview_location_slug.setText("ONLINE EVENT");
} else {
viewHolder.linearlayout_location.setVisibility(View.VISIBLE);
viewHolder.linearlayout_online.setVisibility(View.GONE);
if(obj_current.objLocation != null
&& obj_current.objLocation.locationName != null
&& !obj_current.objLocation.locationName.equalsIgnoreCase(""))
viewHolder.textview_location_slug.setText(obj_current.objLocation.locationName);
}
//display date
//display time
viewHolder.textview_event_time.setText("Time: " + obj_current.startTime);
viewHolder.button_edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Fragment obj_fragment = CreateEventFragment.newInstance(obj_current);
FragmentTransaction fragment_transaction_eventdetails = ((MainActivity) obj_activity)
.getSupportFragmentManager().beginTransaction();
// Get the details of that view to the EventDetailsFragment..
fragment_transaction_eventdetails.replace(R.id.container,
obj_fragment);
fragment_transaction_eventdetails.addToBackStack(obj_fragment
.getClass().getName());
fragment_transaction_eventdetails.commit();
}
});
viewHolder.button_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder((MainActivity) obj_activity)
.setTitle("Quit")
.setMessage("Do you really want to delete this drafted event?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
EventDAO obj_delete_event_dao = new EventDAO(obj_activity);
obj_delete_event_dao.deleteEvent(obj_current.localEventID);
obj_delete_event_dao.closeDbConnection();
al_item_list.remove(position);
notifyDataSetChanged();
}
}).setNegativeButton("No", null).show();
}
});
viewHolder.linearlayout_location
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(obj_activity, "Map intent",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri
.parse("geo:0,0?q=Kothrud"));
obj_activity.startActivity(Intent.createChooser(intent,
"Select "));
}
});
}
#Override
public int getItemCount() {
return al_item_list == null ? 0 : al_item_list.size();
}
/**
* class to hold event list item
*
*
*/
public static class ViewHolder extends RecyclerView.ViewHolder implements
OnClickListener {
public ImageView imageview_event_banner;
public ImageView imageview_bookmark;
public ImageView imageview_call;
public TextView textview_event_name;
// public TextView textview_event_type;
public TextView textview_location_slug;
public TextView textview_event_date;
public TextView textview_event_time;
public Button button_edit;
public Button button_delete;
public LinearLayout linearlayout_location;
public LinearLayout linearlayout_online;
public ViewHolder(View itemView) {
super(itemView);
linearlayout_location = (LinearLayout) itemView
.findViewById(R.id.linearlayout_location);
linearlayout_online = (LinearLayout) itemView
.findViewById(R.id.linearlayout_online);
imageview_event_banner = (ImageView) itemView
.findViewById(R.id.imageview_event_banner);
imageview_bookmark = (ImageView) itemView
.findViewById(R.id.imageview_bookmark);
imageview_call = (ImageView) itemView
.findViewById(R.id.imageview_call);
textview_event_name = (TextView) itemView
.findViewById(R.id.textview_event_name);
textview_event_name.setSelected(true);
textview_location_slug = (TextView) itemView
.findViewById(R.id.textview_location_slug);
textview_location_slug.setSelected(true);
textview_event_date = (TextView) itemView
.findViewById(R.id.textview_event_date);
textview_event_time = (TextView) itemView
.findViewById(R.id.textview_event_time);
button_edit = (Button) itemView
.findViewById(R.id.button_edit);
button_delete = (Button) itemView
.findViewById(R.id.button_delete);
linearlayout_location.setOnClickListener(this);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
itemListener.recyclerViewListClicked(v, getPosition());
}
}
}

Related

Android: Pass text from Textview when clicking an Image button inside recycler view

So I have a recycler view with 2 texts and 1 image button. I want to click the image button and then open a new activity and transfering the text from the textViewADV1 to the next activity
My items .xml in my recyclerview consist of the following
<ImageButton
android:id="#+id/imageButton1"
android:clickable="true"
android:onClick="openActivity2"/>
<TextView
android:id="#+id/textViewADV1"
android:text="Line 1"/>
<TextView
android:id="#+id/textViewADV2"
android:text="Line 2"/>
My openActivity2() from Main Activity
public void openActivity2(View view)
{
Intent intentLoadNewActivity = new Intent(AdvancedResults.this,OpenSelectedAdvanced.class);
startActivity(intentLoadNewActivity);
}
I tried doing textViewADV1.getText().toString() but it only reads the text from the first item in the recycler view
My recycler adapter
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
public String mImage;
public static class AdvancedViewHolder extends RecyclerView.ViewHolder {
public ImageButton mImagebtn;
public TextView mTextView1;
public TextView mTextView2;
public AdvancedViewHolder(View itemView) {
super(itemView);
mImagebtn = itemView.findViewById(R.id.imageButtonADV);
mTextView1 = itemView.findViewById(R.id.textViewADV1);
mTextView2 = itemView.findViewById(R.id.textViewADV2);
}
}
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList) {
mAdvancedList = advancedList;
}
#Override
public AdvancedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.advanced_item, parent, false);
AdvancedViewHolder evh = new AdvancedViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
mImage = "www.testImageURL.com";
Picasso.get().load(mImage).into(holder.mImagebtn);
}
#Override
public int getItemCount() {
return mAdvancedList.size();
}
}
First of all pass a context to your adapter when you initialize it:
//in the main activity that you initialize the adapter in
AdvancedAdapter adapter = new AdvancedAdapter(your_list , MainActivity.this);
Now change the constructor of AdvancedAdapter to accept context
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
private Context context;
.............
//constructor
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList,Context context) {
mAdvancedList = advancedList;
this.context = context;
}
Now in onBindViewHolder in the AdvancedAdapter
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
mImage = "www.testImageURL.com";
Picasso.get().load(mImage).into(holder.mImagebtn);
//on click image button
hodler.mImagebtn.setOnclickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Intent intent = new Intent(context , OpenSelectedAdvanced.class);
intent.putExtra("data" , currentItem.getText1());
context.startActivity(intent);
}
});
}
To get the data from OpenSelectedAdvanced activity:
//in oncreate method:
Intent intent = getIntent();
//this is your text view text that came from the clicked image button
String transferedText = intent.getStringExtra("data");
If you have declared your onBindViewHolder() in your adapter class so why are you starting activity from MainActivity. You should add setOnclicklistenr() in onBindViewHolder() to achieve the desired result that you want that is in following way :
public class AdvancedAdapter extends RecyclerView.Adapter<AdvancedAdapter.AdvancedViewHolder> {
private ArrayList<AdvancedItem> mAdvancedList;
//one more thing you have to create Context field so that you can
//you can start the activity from any context (From Any activity)
private Context mContext;
public String mImage;
public static class AdvancedViewHolder extends RecyclerView.ViewHolder {
public ImageButton mImagebtn;
public TextView mTextView1;
public TextView mTextView2;
public AdvancedViewHolder(View itemView) {
super(itemView);
mImagebtn = itemView.findViewById(R.id.imageButtonADV);
mTextView1 = itemView.findViewById(R.id.textViewADV1);
mTextView2 = itemView.findViewById(R.id.textViewADV2);
}
}
public AdvancedAdapter(ArrayList<AdvancedItem> advancedList, Context mContext) {
mAdvancedList = advancedList;
this.mContext = mContext;
}
#Override
public AdvancedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.advanced_item, parent, false);
AdvancedViewHolder evh = new AdvancedViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(AdvancedViewHolder holder, int position) {
AdvancedItem currentItem = mAdvancedList.get(position);
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
mImage = "www.testImageURL.com";
holder.mImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here You start your activity
Intent intent = new Intent(mContext, Activity2.class);
//you can putExtras here
mContext.startActivity(intent);
});
Picasso.get().load(mImage).into(holder.mImagebtn);
}
#Override
public int getItemCount() {
return mAdvancedList.size();
}
}
Now initialize this adapter in your activity where you implemented recyclerView And Send that arraylist into the parameters of that constructor of your adapter :) if did not understand yet you can try the tutorial on the link given below : https://www.youtube.com/watch?v=bIppSKk9afI

Recycler list stucks allot while scrolling

I have added simple v7.widget.RecyclerView and set the adapter simply but while scrolling the list it jerks allot, scrolling is not working out smoothly. Infact I used few library as well for fast scrolling but nothing works. I have picasso inside adapter to load images while data setting or handling visibility is done in "onBindViewHolder".
If someone have better solution than kindly help me out.
I already tried all the below methods but none of them works
#BindView(R.id.rv_list)
RecyclerView rvList;
ViewCompat.setNestedScrollingEnabled(rvList, false);
rvList.setNestedScrollingEnabled(false);
rvList.setHasFixedSize(true);
rvList.setItemViewCacheSize(20);
rvList.setDrawingCacheEnabled(true);
rvList.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Below is my Adapter Code:
public class RecyclerAdapter extends RecyclerView.Adapter<cadapter.RecyclerAdapter.MyViewHolder> {
Context ctx;
ArrayList<Model> Modelslist;
GlobalClass gc;
View itemView;
View parentView;
private RecyclerAdapter.RecyclerAdapterListener listener;
PrefManager prefManager;
public RecyclerAdapter(Context context, ArrayList<Model> Modelslist, RecyclerAdapter.RecyclerAdapterListener listener) {
this.Modelslist = Modelslist;
this.ctx = context;
gc = GlobalClass.getInstance();
this.listener = listener;
prefManager = new PrefManager(context);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public RecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout, parent, false);
if (itemView == null) {
parentView = new RelativeLayout(this.ctx);
} else {
parentView = (RelativeLayout) itemView;
}
return new RecyclerAdapter.MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final RecyclerAdapter.MyViewHolder holder, final int position) {
final Model cat = this.Modelslist.get(position);
holder.txtNumber.setText(cat.getNumber());
holder.txtName.setText(cat.getName());
final String flagPath = cat.getFlag();
if(cat.getForwarding1().equals("0")) {
holder.callForwardingSwitch.setChecked(true);
holder.txtCallRateVal.setText(cat.getForwardingCost());
holder.txtCallRateVal.setVisibility(View.VISIBLE);
holder.txtCallRate.setVisibility(View.VISIBLE);
holder.txtCallRateVal2.setVisibility(View.VISIBLE);
holder.txtCallRateVal2.setTextColor(ctx.getResources().getColor(R.color.text_grey));
////VISIBLE call Forwading Text
holder.txtCallRateVal.setVisibility(View.VISIBLE);
holder.txtCallRate.setVisibility(View.VISIBLE);
}else{
holder.callForwardingSwitch.setChecked(false);
////Hide call Forwading Text
holder.txtCallRateVal.setVisibility(View.INVISIBLE);
holder.txtCallRate.setVisibility(View.INVISIBLE);
holder.txtCallRateVal2.setVisibility(View.INVISIBLE);
}
holder.txtNumberDesc.setText(cat.getDetails());
holder.txtRenewDate.setText(cat.getrenewal_date());
holder.txtSetupVal.setText(cat.getcost());
holder.txtMonthlyVal.setText(cat.getmonthlycost());
String application_status= cat.getapplication_status();
System.out.println("Application status:::::: "+ application_status+" number: "+cat.getNumber());
if(application_status.equals("0")){
holder.txtStatus.setText("* Pending Approval");
holder.txtStatus.setVisibility(View.VISIBLE);
holder.txtStatus.setTextColor(ctx.getResources().getColor(R.color.account_error));
holder.txtCallRateVal.setVisibility(View.INVISIBLE);
holder.txtCallRateVal2.setVisibility(View.INVISIBLE);
holder.txtCallRate.setVisibility(View.INVISIBLE);
////////Unclicking Highlight Delete and call Forwarding
holder.Delete.setBackgroundResource(R.drawable.number_delete_gray);
holder.Delete.setClickable(false);
holder.callForwardingSwitch.setChecked(false);
holder.callForwardingSwitch.setClickable(false);
// holder.callForwardingSwitch.setHighlightColor(ctx.getResources().getColor(R.color.text_dark_grey));
/////////Visible Tag
holder.rel__number_status.setVisibility(View.VISIBLE);
holder.rel__number_status.setBackground(ctx.getDrawable(R.drawable._submitted_tag));
holder.txtNumberStatus.setText("Registration Submitted *");
/////// Hide Renew Date:
holder.txtRenew.setVisibility(View.GONE);
holder.txtRenewDate.setVisibility(View.GONE);
}else if(application_status.equals("1")){
holder.txtStatus.setText("Click here to complete number registration");
holder.txtStatus.setVisibility(View.VISIBLE);
/////////Visible Tag
holder.rel__number_status.setVisibility(View.VISIBLE);
holder.rel__number_status.setBackground(ctx.getDrawable(R.drawable._saved_tag));
holder.txtNumberStatus.setText("Registration Incomplete");
/////// Hide Renew Date:
holder.txtRenew.setVisibility(View.GONE);
holder.txtRenewDate.setVisibility(View.GONE);
holder.txtStatus.setTextColor(ctx.getResources().getColor(R.color.app_header));
}else if(application_status.equals("2")){//////Approved///
//holder.txtStatus.setText("Approved");
holder.txtStatus.setVisibility(View.VISIBLE);
holder.txtStatus.setText("Active");
holder.txtStatus.setTextColor(ctx.getResources().getColor(R.color.green600));
/////////Hide Tag
holder.rel__number_status.setVisibility(View.INVISIBLE);
holder.txtSetupVal.setVisibility(View.GONE);
holder.txtSetup.setVisibility(View.GONE);
/////// VISIBLE Renew Date:
holder.txtRenew.setVisibility(View.VISIBLE);
holder.txtRenewDate.setVisibility(View.VISIBLE);
}else if(application_status.equals("3")){///// Rejected///
//holder.txtStatus.setText("Rejected");
/////////Hide Tag
holder.txtStatus.setVisibility(View.INVISIBLE);
holder.rel__number_status.setVisibility(View.INVISIBLE);
/////// VISIBLE Renew Date:
holder.txtRenew.setVisibility(View.VISIBLE);
holder.txtRenewDate.setVisibility(View.VISIBLE);
}else{
if(cat.getLocal().equals("1") && cat.getAddress().equals("1")
&& cat.getPhoto().equals("1") && cat.getapplication_status().equals("-1")){
holder.txtStatus.setVisibility(View.VISIBLE);
holder.txtStatus.setText("Active");
holder.txtStatus.setTextColor(ctx.getResources().getColor(R.color.green600));
holder.rel__number_status.setVisibility(View.INVISIBLE);
holder.txtSetupVal.setVisibility(View.GONE);
holder.txtSetup.setVisibility(View.GONE);
}else{
holder.txtStatus.setText("");
/////////Hide Tag
holder.txtStatus.setVisibility(View.INVISIBLE);
holder.rel__number_status.setVisibility(View.INVISIBLE);
}
}
System.out.println("Flag::::::::::: "+ flagPath);
/*Picasso.with(ctx)
.load(flagPath) // thumbnail url goes here
.into(holder.CountryFlagim, new Callback() {
#Override
public void onSuccess() {
Picasso.with(ctx)
.load(flagPath) // image url goes here
.placeholder(holder.CountryFlagim.getDrawable())
.into(holder.CountryFlagim);
}
#Override
public void onError() {
}
});*/
Glide
.with(ctx)
.load(flagPath)
.centerCrop()
.placeholder(holder.CountryFlagim.getDrawable())
.into(holder.CountryFlagim);
//Picasso.with(ctx).load(flagPath).into(holder.CountryFlagim);
applyClickEvents(holder,position);
}
#Override
public int getItemCount() {
if (this.Modelslist != null) {
return this.Modelslist.size();
} else {
return 0;
}
}
private void applyClickEvents(final RecyclerAdapter.MyViewHolder holder, final int position) {
holder.mainFrame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.moveToDetailScreen(position);
}
});
holder.Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Model cat = Modelslist.get(position);
}
});
holder.callForwardingSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
System.out.println("Call forwarding switch: "+ b);
}
});
}
public interface NumberListAdapterListener {
void deleteItem(int position);
void moveToDetailScreen(int position);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
RelativeLayout rel__number,rel__setup,rel__number_status;
ImageView CountryFlagim;
TextView txtNumber, txtName;
SwitchCompat callForwardingSwitch;
TextView txtNumberDesc;
TextView txtSetupVal, txtSetup;
TextView txtMonthlyVal;
TextView txtCallRateVal, txtCallRateVal2, txtCallRate;
TextView txtStatus;
TextView txtNumberStatus, txtRenewDate, txtRenew;
Button Delete;
RelativeLayout mainFrame;
public MyViewHolder(View v) {
super(v);
rel__number = (RelativeLayout) v.findViewById(R.id.rel__number);
rel__setup = (RelativeLayout) v.findViewById(R.id.rel__setup);
rel__number_status = (RelativeLayout) v.findViewById(R.id.rel__number_status);
CountryFlagim = (ImageView) v.findViewById(R.id.CountryFlagim);
txtNumber = (TextView) v.findViewById(R.id.txtNumber);
txtName = (TextView) v.findViewById(R.id.txtName);
txtNumberDesc = (TextView) v.findViewById(R.id.txtNumberDesc);
txtSetupVal = (TextView) v.findViewById(R.id.txtSetupVal);
txtSetup = (TextView) v.findViewById(R.id.txtSetup);
txtMonthlyVal = (TextView) v.findViewById(R.id.txtMonthlyVal);
txtCallRate = (TextView) v.findViewById(R.id.txtCallRate);
txtCallRateVal = (TextView) v.findViewById(R.id.txtCallRateVal);
txtCallRateVal2 = (TextView) v.findViewById(R.id.txtCallRateVal2) ;
txtStatus = (TextView) v.findViewById(R.id.txtStatus);
txtNumberStatus = (TextView) v.findViewById(R.id.txtNumberStatus);
Delete = (Button) v.findViewById(R.id.Delete);
callForwardingSwitch = (SwitchCompat) v.findViewById(R.id.callForwardingSwitch);
mainFrame = (RelativeLayout) v.findViewById(R.id.mainFrame);
txtRenewDate = (TextView) v.findViewById(R.id.txtRenewDate);
txtRenew = (TextView) v.findViewById(R.id.txtRenew);
}
}
}
You can try Glide. Glide doesn't load full size picture and uses less memory, which should be faster than Picasso.

How to pass the view Id from Recycler Adapter to Activity?

I am trying to pass view Id from Recyclerview Adapter to Activity,when the Recycler view List item is clicked.
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> implements FastScrollRecyclerView.SectionedAdapter{
public interface OnRecyclerItemClickListener {
void onRecyclerItemClick(User data,int id);
}
List<User> dataSource;
private OnRecyclerItemClickListener onRecyclerItemClickListener;
private Context context;
public ActiveBeepsAdapter(List<User> dataArgs, OnRecyclerItemClickListener onRecyclerItemClickListener,Context context) {
this.dataSource = dataArgs;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_active_message, parent, false);
ViewHolder viewHolder = new ViewHolder(view, onRecyclerItemClickListener);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
User user = dataSource.get(position);
holder.tvId.setText(user.getId());
Picasso.with(context)
.load(user.getProfilePicUrl())
.placeholder(R.drawable.bg_logo)
.error(R.drawable.bg_logo)
.transform(new CircleTransform())
.into(holder.ivUserProfile);
}
#Override
public int getItemCount() {
return dataSource.size();
}
#NonNull
#Override
public String getSectionName(int i) {
return String.valueOf(dataSource.get(i).getId().charAt(0));
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private OnRecyclerItemClickListener onRecyclerItemClickListener;
User data = new User();
TextView tvId;
ImageView ivUserProfile;
public ViewHolder(View itemView, OnRecyclerItemClickListener onRecyclerItemClickListener) {
super(itemView);
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
tvId = (TextView)itemView.findViewById(R.id.tvName);
ivUserProfile = (ImageView)itemView.findViewById(R.id.ivProfilePic);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
User user = dataSource.get(position);
int id = v.getId();
onRecyclerItemClickListener.onRecyclerItemClick(user,id);
}
}
}
Suppose, If the Profile Image is clicked, the view id should sent to activity..
And My Activity
#EActivity
public class ActiveMessage extends AppCompatActivity implements Adapter.OnRecyclerItemClickListener{
#ViewById(R.id.toolbar)
Toolbar toolbar;
#ViewById(R.id.rvactiveMessage)
FastScrollRecyclerView rvmessage;
List<User> allUser;
#ViewById(R.id.toolbar_title)
TextView tv_toolbar;
#AfterViews
protected void init(){
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_drop_down_black_24dp));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tv_toolbar.setText("Active Message");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
allUser = new ArrayList<>();
User user;
String fullName[] = {"ajay","kamal","akhil"};
String id[] = {"its_ajay","its_kamal","its_akhil"};
for(int i=0;i<id.length;i++){
user = new User();
user.setId(id[i]);
user.setFullName(fullName[i]);
allUser.add(user);
}
Adapter adapter = new Adapter(allUser,this,getApplicationContext());
rvmessage.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rvmessage.setAdapter(activeBeepsAdapter);
}
#Override
public void onRecyclerItemClick(User data,int id) {
if (!Utils.isNetworkAvailable(getApplicationContext())) {
noInternet();
}
// tvName has multiple Implementation
if (id == R.id.tvName){
Log.d("Id",data.getId());
}
}
public void noInternet(){
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.alert_dialog);
dialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_active_message);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
In my Activity, If the ProfileImage is clicked, pop up the dialog box.
Also, i need to check if there is Internet Connection when the list Item is clicked.
In adapter onClick method instead of id pass view:
#Override
public void onClick(View v) {
int position = getAdapterPosition();
User user = dataSource.get(position);
int id = v.getId();
onRecyclerItemClickListener.onRecyclerItemClick(user,v);
}
Now in Activity
#Override
public void onRecyclerItemClick(User data,View view) {
if (!Utils.isNetworkAvailable(getApplicationContext())) {
noInternet();
}
// tvName has multiple Implementation
if (view.getId() == R.id.tvName){
Log.d("Id",data.getId());
}
}

How can I pass the data from view to another activity?

I have used CardView inside a RecyclerView in horizontal manner. Now what I want to do is, when user click on a card then the data which I have putted into the intent with the help of putExtra function should be passed to the next activity.
Here is the code
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private List<Section> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, List<Section> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
Section singleItem = itemsList.get(i);
holder.tvTitle.setText(singleItem.getName());
holder.tvAuthor.setText(singleItem.getAuthorname());
holder.tvPremium.setText(singleItem.getPremium());
Glide.with(mContext)
.load(singleItem.getImage()
.into(holder.itemImage);
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView tvTitle, tvAuthor, tvPremium;
protected ImageView itemImage;
public SingleItemRowHolder(final View view) {
super(view);
this.tvTitle = (TextView) view.findViewById(R.id.tvTitle1);
this.tvAuthor = (TextView) view.findViewById(R.id.tvTitle2);
this.tvPremium = (TextView) view.findViewById(R.id.txtSubText1);
this.itemImage = (ImageView) view.findViewById(R.id.itemImage);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), BooksDescription.class);
intent.putExtra("id", NavigationDrawer.ID.get());
mContext.startActivity(intent);
}
});
}
}
}
Here in the line intent.putExtra("id", NavigationDrawer.ID); NavigationDrawe.ID having 20 integer data. Now which function should I use to get the data of only those card which is clicked.

How to add click to RecyclerView whole row and a specific row item separately?

I have a RecyclerView with two TextViews and one ImageView. I want to add separate click to whole each row and the ImageViewin each row seperately. Is it possible?
Here is my Adapter class:
public class ContactsListAdapter extends RecyclerView.Adapter<ContactsListAdapter.MyViewHolder> {
private List<ContactsDataModel> dataList;
private Typeface tfSegoeui;
Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, detail;
public ImageView catIcon, imgCall;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
detail = (TextView) view.findViewById(R.id.detail);
catIcon = (ImageView) view.findViewById(R.id.catIcon);
imgCall = (ImageView) view.findViewById(R.id.imgCall);
}
}
public ContactsListAdapter(Context context, List<ContactsDataModel> dataList) {
this.dataList = dataList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.contacts_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
ContactsDataModel dataModel = dataList.get(position);
tfSegoeui = Typeface.createFromAsset(holder.title.getContext().getResources().getAssets(), "fonts/segoeui.ttf");
holder.title.setText(dataModel.getName());
holder.detail.setText(dataModel.getPersonalNumber());
holder.imgCall.setTag(dataModel.getPersonalNumber());
holder.catIcon.setImageResource(dataModel.getImage());
holder.title.setTypeface(tfSegoeui);
holder.detail.setTypeface(tfSegoeui);
holder.imgCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String number = holder.imgCall.getTag().toString();
Log.d("number", number);
String num = "tel:" + number;
try {
Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(num));
context.startActivity(dialIntent);
}catch(Exception e) {
Toast.makeText(context,"Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
EndCallListener callListener = new EndCallListener();
TelephonyManager mTM = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
}
});
}
#Override
public int getItemCount() {
return dataList.size();
}
private class EndCallListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
String LOG_TAG = "Call contact ";
if(TelephonyManager.CALL_STATE_RINGING == state) {
Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
}
if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
//wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
Log.i(LOG_TAG, "OFFHOOK");
}
if(TelephonyManager.CALL_STATE_IDLE == state) {
//when this state occurs, and your flag is set, restart your app
Log.i(LOG_TAG, "IDLE");
}
}
}
}
Set your single row layout file as
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, detail;
public ImageView catIcon, imgCall;
//add item_row layout e.g
public RelativeLayout rel;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
detail = (TextView) view.findViewById(R.id.detail);
catIcon = (ImageView) view.findViewById(R.id.catIcon);
imgCall = (ImageView) view.findViewById(R.id.imgCall);
rel= (RelativeLayout) view.findViewById(your_id_here);
rel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//whatever you want here
}
});
}
}
Please refer the below code for item click event.
ContactsListAdapter
private List<ContactsDataModel> dataList;
private Typeface tfSegoeui;
Context context;
public interface OnContactClick {
public void onContactClick(int position);
}
OnContactClick onContactClick;
public void setOnContactClick(OnContactClick onContactClick) {
this.onContactClick = onContactClick;
}
Add this in onBindViewHolder
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
ContactsDataModel dataModel = dataList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(onContactClick != null) {
onContactClick.onContactClick(position);
}
}
});
Add below line in activity
ContactsListAdapter contactsListAdapter = new ContactsListAdapter(this, dataList);
contactsListAdapter.setOnContactClick(new ContactsListAdapter.OnContactClick() {
#Override
public void onContactClick(int position) {
//You will receive event when clicking item in list
}
});
you can add to click listener to any view like this inside ViewHolder class
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, detail;
public ImageView catIcon, imgCall;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
detail = (TextView) view.findViewById(R.id.detail);
catIcon = (ImageView) view.findViewById(R.id.catIcon);
imgCall = (ImageView) view.findViewById(R.id.imgCall);
imgCall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
title.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
catIcon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
detail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
}
}
and if you want position of the item clicked.
add this line inside your onBindViewHolder
title.setTag(position);
get position using title.getTag()
save
View itemView
in the holder and do setonclick like you did with the imgCall
also you did two onclick listeners on imgCall

Categories

Resources