RecyclerView isn't fixed to top when Items are added - android

I have this RecyclerView that doesn't want to show the item at position 0 anymore, after enough items are added to make the RecyclerView scrollable. Instead it seems to stick to the bottom item and scroll down with this one, although the other items are added at position 0.
public class hauptseite extends AppCompatActivity {
private ArrayList<ExampleItem> mExampleList;
private RecyclerView mRecyclerView;
private ExampleAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ImageButton btnInput;
private EditText editTextInput;
private int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
createExampleList();
buildRecyclerView();
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
btnInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editTextInput.getText().toString();
insertItem(name);
}
});
}
public void insertItem(String name) {
mExampleList.add(position, new ExampleItem(name));
mAdapter.notifyItemInserted(position);
editTextInput.setText("");
}
public void removeItem(int position) {
mExampleList.remove(position);
mAdapter.notifyItemRemoved(position);
}
public void createExampleList() {
mExampleList = new ArrayList<>();
}
public void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerName);
mRecyclerView.setHasFixedSize(false);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener(){
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
});
}
And the adapter
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public TextView mTextView1;
public ImageView mDeleteName;
public ExampleViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.name_added);
mDeleteName = itemView.findViewById(R.id.delete_name);
mDeleteName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onDeleteClick(position);
}
}
}
});
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList) {
mExampleList = exampleList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mTextView1.setText(currentItem.getName1());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
So what do I need change when I want my RecyclerView to stay at the item in position 0 unless I start scrolling down?

You can scroll to the desired position on the insert:
mLayoutManager.scrollToPosition(yourPosition)

there is easy way to fix that.
do not add item at position 0 ... just reverse the default order of your recyclerView
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
yourRecyclerView.setLayoutManager(linearLayoutManager);

I see two good ways of solving this:
One: Don't hold position in your activity, but use the size of the ArrayList
public void insertItem(String name) {
mExampleList.add(new ExampleItem(name));
mAdapter.notifyItemInserted(mExampleList.size() - 1);
editTextInput.setText("");
}
Two: Move the example list and its methods into your adapter. This way you can also remove the interface for deletion and let the adapter handle it all. I also added a method to retrieve the current list of items from the adapter incase you need that data outside of the adapter.
Activity:
public class hauptseite extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ExampleAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ImageButton btnInput;
private EditText editTextInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
buildRecyclerView();
btnInput = findViewById(R.id.btn_add);
editTextInput = findViewById(R.id.name_add);
btnInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editTextInput.getText().toString();
mAdapter.insertItem(name);
}
});
}
public void removeItem(int position) {
mAdapter.notifyItemRemoved(position);
}
public void createExampleList() {
mExampleList = new ArrayList<>();
}
public void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerName);
mRecyclerView.setHasFixedSize(false);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter();
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
And the adapter:
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
public insertItem(String name) {
mExampleList.add(name);
this.notifyItemAdded(mExampleList.size() -1)
}
public removeItem(int position) {
mExampleList.remove(position);
this.notifyItemRemoved(position);
}
public ArrayList<ExampleItems> getItems() {
return mExampleList();
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public TextView mTextView1;
public ImageView mDeleteName;
public ExampleViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
mTextView1 = itemView.findViewById(R.id.name_added);
mDeleteName = itemView.findViewById(R.id.delete_name);
mDeleteName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
removeItem(position);
}
}
}
});
}
}
public ExampleAdapter() {
mExampleList = new ExampleList();
}

Related

How can i get the all value of Recyclerview on Button click?

public class MainActivity extends Activity implements
GetDataContract.View,RecyclerItemClickListener {
private Presenter mPresenter;
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
CountryAdapter countryAdapter;
EditText etEnterName;
Button btAddItem;
List<CountryRes> allCountriesEditValue;
List<CountryRes> allCountriesData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getView();
}
private void getView() {
/*presentator */
mPresenter = new Presenter(this);
/*initiliaze of id*/
recyclerView = (RecyclerView) findViewById(R.id.recycler);
etEnterName = (EditText) findViewById(R.id.etEnterName);
btAddItem = (Button) findViewById(R.id.btAddItem);
linearLayoutManager = new LinearLayoutManager(this);
/*initiliaze the arraylist*/
allCountriesData=new ArrayList<>();
recyclerView.setLayoutManager(linearLayoutManager);
btAddItem.setOnClickListener(new AddButtonClick());
}
#Override
public void onGetDataFailure(String message) {
Log.d("Status", message);
}
#Override
public void onGetDataSuccess(String message, List<CountryRes>
allCountriesData) {
/*add the value mannulay*/
CountryRes countryRes = new CountryRes();
countryRes.setName(etEnterName.getText().toString());
allCountriesData.add(countryRes);
countryAdapter = new CountryAdapter(getApplicationContext(),
allCountriesData, (RecyclerItemClickListener) this);
recyclerView.setAdapter(countryAdapter);
/*set the data in the room*/
AppDataBase database = AppDataBase.getAppDatabase(this);
DataGenerator.with(database).generateCats(allCountriesData);
Logger.displayCatsInLog(database.catDao().loadAll());
countryAdapter.notifyDataSetChanged();
}
/*on item click*/
#Override
public void onDashBoardItemClick(String pos) {
Bundle bundle = new Bundle();
bundle.putString("TABVALUE", pos);
Intent intent = new Intent(getApplicationContext(),
DynamicTabsActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
private class AddButtonClick implements View.OnClickListener {
#Override
public void onClick(View view) {
mPresenter.getDataFromURL(getApplicationContext(), "");
}
}
}
class adapter
public class CountryAdapter extends
RecyclerView.Adapter<CountryAdapter.MyViewHolder> {
private Context context;
private List<CountryRes> list = new ArrayList<>();
private List<CountryRes> list_edit = new ArrayList<>();
private RecyclerItemClickListener onRecyclerItemClickListener;
public CountryAdapter(Context context, List<CountryRes> list,
RecyclerItemClickListener onRecyclerItemClickListener) {
this.context = context;
this.list = list;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
}
#Override
public CountryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View layoutView;
layoutView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent,
false);
return new FooterViewHolder(layoutView,
onRecyclerItemClickListener);
}
#Override
public void onBindViewHolder(CountryAdapter.MyViewHolder holder, int
position) {
holder.tvCountryName.setText(list.get(position).getName());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvCountryName;
LinearLayout llListItem;
public MyViewHolder(View itemView) {
super(itemView);
tvCountryName = (TextView)
itemView.findViewById(R.id.tv_country_name);
llListItem = (LinearLayout)
itemView.findViewById(R.id.llListItem);
}
}
private class FooterViewHolder extends MyViewHolder {
public FooterViewHolder(View layoutView, final
RecyclerItemClickListener onRecyclerItemClickListener) {
super(layoutView);
llListItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onRecyclerItemClickListener != null) {
onRecyclerItemClickListener.onDashBoardItemClick(tvCountryName.getText().toS
tring());
}
}
});
}
}
}
Interface
public interface RecyclerItemClickListener {
void onDashBoardItemClick(String pos);
}
Case 1: Inside ViewHolder if you need to understand exactly position of clicked item you could call getAdapterPosition().
Case 2: You just need to receive all items of adapter. It is simple, make getter method which will return the items.
Case 3: Send info to activity, first make some specific event listener of your view inside ViewHolder, then event triggers (user clicks or other) and you call your interface method which you passed inside adapter, that was implemented in activity.
Tell me if you need an example, i will do it.
Try this one,
Button button= (Button) findViewById(R.id.your_button_id);
button.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
//create new ArrayList.
//ArrayList<CountryRes> showList=new ArrayList<>;
//now, put all stored data of a list in this arraylist.
showList.addAll(allCountriesData);
}
});

How to render render JSON data using retrofit and recylerview in android studio

I am trying use retrofit and recyclerview to display from a web app. I have the following models:
Main Activities
public class ProfileActivity extends AppCompatActivity {
private SalesAdapter mAdapter;
private RecyclerView mRecyclerView;
private SaleService mService;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView(R.layout.activity_profile );
mService = ApiUtils.getSaleService();
mRecyclerView = (RecyclerView) findViewById(R.id.rvItems);
mAdapter = new SalesAdapter(this, new ArrayList<Sale>(0), new SalesAdapter.ItemListener() {
#Override
public void onPostClick(long id) {
}
});
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
loadAnswers();
}
public void loadAnswers() {
mService.getSales().enqueue(new Callback<List<Sale>>() {
#Override
public void onResponse(Call<List<Sale>> call, Response<List<Sale>> response) {
if(response.isSuccessful()) {
mAdapter.UpdateSales(response.body());
} else {
int statuscode = response.code();
}
}
#Override
public void onFailure(Call<List<Sale>> call, Throwable t) {
}
});
}
}
Recyclerview Adapter
public class SalesAdapter extends RecyclerView.Adapter<SalesAdapter.ViewHolder>{
private Context mContext;
private List<Sale> mSales;
private ItemListener mItemListener;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView tvLocaleName;
ItemListener mItemListener;
public ViewHolder(View itemView, ItemListener itemListener) {
super(itemView);
tvLocaleName = (TextView) itemView.findViewById(android.R.id.text1);
this.mItemListener = itemListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Sale sale = getSales(getAdapterPosition());
this.mItemListener.onPostClick(sale.getId());
notifyDataSetChanged();
}
}
public SalesAdapter(Context mContext, List<Sale> mSales, ItemListener mItemListener) {
this.mContext = mContext;
this.mSales = mSales;
this.mItemListener = mItemListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view, this.mItemListener);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Sale sale = mSales.get(position);
TextView textView = holder.tvLocaleName;
textView.setText(sale.getLocaleName());
}
#Override
public int getItemCount() {
return mSales.size();
}
public void UpdateSales(List<Sale> sales) {
mSales = sales;
}
private Sale getSales(int position) {
return mSales.get(position);
}
public interface ItemListener {
void onPostClick(long id);
}
}
from the image you can see that i am able to get back the data, but how do I display in it the recyclerview? where am i going wrong with code?
Add a notifyDataSetChanged() call to your adapter after you refresh the list.
Your method should look like:
public void UpdateSales(List<Sale> sales) {
mSales = sales;
notifyDataSetChanged();
}
Check out this link to learn more about this method.

RecyclerView dosent show any elements following is my code

Fragment_bookmovie2.java
public class Fragment_bookmovie2 extends android.support.v4.app.Fragment implements View.OnClickListener {
private static final String TAG ="Fragment_bookmovie2" ;
ArrayList<String> moviename= new ArrayList<>();
ArrayList<String> movieyear= new ArrayList<>();
ArrayList<String> moviebanner= new ArrayList<>();
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
Movie_listAdapter2 adapter ;
LinearLayout progress;
RelativeLayout ll;
public Fragment_bookmovie2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.e(TAG,"reched on create");
// first step - retrieve object
Backendless.Persistence.of(Booking.class).find(new AsyncCallback<BackendlessCollection<Booking>>() {
#Override
public void handleResponse(BackendlessCollection<Booking> response) {
for(Booking booking : response.getData()) {
if(!moviename.contains(booking.getMovie().get(0).getMovie_Name())) {
moviename.add(booking.getMovie().get(0).getMovie_Name());
movieyear.add(booking.getMovie().get(0).getYear());
moviebanner.add("https://api.backendless.com/" + BackendSetting.APPLICATION_ID + "/" + BackendSetting.VERSION + "/files/mypics/" + booking.getMovie().get(0).getImage());
}
}
adapter.notifyDataSetChanged();
ll.removeView(progress);
}
#Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(getActivity(), fault.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
moviename.add("haha");
movieyear.add("hello");
moviebanner.add("http://www.w3schools.com/css/trolltunga.jpg");
// Inflate the layout for this fragment
ll = (RelativeLayout) inflater.inflate(R.layout.fragment_bookmovie2, container, false);
progress = (LinearLayout) ll.findViewById(R.id.progress_bookingFrag);
recyclerView = (RecyclerView) ll.findViewById(R.id.recycle_movielist);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new Movie_listAdapter2(getActivity(),moviename,movieyear,moviebanner);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return ll;
}
#Override
public void onClick(View view) {
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
/*#Override
public void onButtonClickListnerProceed(Integer pos) {
Intent booking_screen_redirect = new Intent(getActivity(), BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(pos));
this.onPause();
startActivity(booking_screen_redirect);
getActivity().overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}*/
}
Movie_listAdapter2.java
public class Movie_listAdapter2 extends RecyclerView.Adapter<Movie_listAdapter2.Movie_cards>{
final static String TAG="Movie_listAdapter2";
Context context_external;
ArrayList<String> moviename=new ArrayList<>();
ArrayList<String> movieyear=new ArrayList<>();
ArrayList<String> banner=new ArrayList<>();
public Movie_listAdapter2(Context context,ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
//set the context and the format of the layout inside the list item
//i.e R.layout.movie_list_adapter
//also the resource i.e the item names in an ArrayList
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
this.context_external=context;
Log.e(TAG,"size = "+movieyear.size()+" "+moviename.size());
}
public static class Movie_cards extends RecyclerView.ViewHolder {
CardView cv;
TextView movie_name;
TextView movie_year;
Button proceed;
ImageView movie_banner;
public Movie_cards(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.movie_list_card);
movie_name = (TextView)itemView.findViewById(R.id.tv_card_moviename);
movie_year = (TextView)itemView.findViewById(R.id.tv_card_movieyear);
movie_banner = (ImageView)itemView.findViewById(R.id.card_moviebanner);
proceed = (Button) itemView.findViewById(R.id.b_card_proceed);
}
}
#Override
public Movie_cards onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_card, parent, false);
Movie_cards pvh = new Movie_cards(v);
return pvh;
}
public void updateData(ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(final Movie_cards holder, final int position) {
holder.movie_name.setText(moviename.get(position));
holder.movie_year.setText(movieyear.get(position));
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.networkPolicy(NetworkPolicy.OFFLINE)
.error(R.drawable.placeholder)
.fit()
.into(holder.movie_banner, new Callback() {
#Override
public void onSuccess() {
//i.e image was loaded from cache
}
#Override
public void onError() {
//image was downloaded as it wasn't available in cache
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.error(R.drawable.warning)
.fit()
.into(holder.movie_banner);
}
});
holder.proceed.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent booking_screen_redirect = new Intent(context_external, BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(position));
context_external.startActivity(booking_screen_redirect);
//overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
});
}
#Override
public int getItemCount() {
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
the fragment displays empty and no items appear even though i have added the data to arraylists and passed to the adapter. please help . thanks in advance
Problem is in below code you are returning 0 that's why its not showing any item
#Override
public int getItemCount() {
return 0;
}
You should return your list's size here either moviename.size(); or movieyear.size()

OnClick action gives error in recycler grid layout

This is My MainActivity Code.In this we get error in setOnItemClickListener as null pointer exception and it stops my app.give me some suggestions where am i wrong. I am trying to achieve custom grid with image on top and title next to it.
public class MainActivity extends AppCompatActivity {
//RecyclerView recyclerView;
private static final String TAG = "MainActivity";
private final String android_version_names[] = {
"Donut",
"Eclair",
"Froyo",
"Gingerbread",
"Honeycomb",
"Ice Cream Sandwich",
"Jelly Bean",
"KitKat",
"Lollipop",
"Marshmallow"
};
private final String android_image_urls[] = {
"https://api.learn2crack.com/android/images/donut.png",
"https://api.learn2crack.com/android/images/eclair.png",
"https://api.learn2crack.com/android/images/froyo.png",
"https://api.learn2crack.com/android/images/ginger.png",
"https://api.learn2crack.com/android/images/honey.png",
"https://api.learn2crack.com/android/images/icecream.png",
"https://api.learn2crack.com/android/images/jellybean.png",
"https://api.learn2crack.com/android/images/kitkat.png",
"https://api.learn2crack.com/android/images/lollipop.png",
"https://api.learn2crack.com/android/images/marshmallow.png"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
recyclerView.setLayoutManager(layoutManager);
ArrayList<AndroidVersion> androidVersions = prepareData();
DataAdapter adapter = new DataAdapter(getApplicationContext(),androidVersions);
recyclerView.setAdapter(adapter);
DataAdapter mAdapter = null ;
mAdapter.setOnItemClickListener(new DataAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.d(TAG, "onItemClick position: " + position);
}
});
}
private ArrayList<AndroidVersion> prepareData(){
ArrayList<AndroidVersion> android_version = new ArrayList<>();
for(int i=0;i<android_version_names.length;i++){
AndroidVersion androidVersion = new AndroidVersion();
androidVersion.setAndroid_version_name(android_version_names[i]);
androidVersion.setAndroid_image_url(android_image_urls[i]);
android_version.add(androidVersion);
}
return android_version;
}
}
This Is My Adapter Code.
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<AndroidVersion> android;
private Context context;
private static ClickListener clickListener;
public DataAdapter(Context context,ArrayList<AndroidVersion> android) {
this.android = android;
this.context = context;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_android.setText(android.get(i).getAndroid_version_name());
Picasso.with(context).load(android.get(i).getAndroid_image_url()).resize(240, 120).into(viewHolder.img_android);
}
#Override
public int getItemCount() {
return android.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView tv_android;
private ImageView img_android;
public ViewHolder(View view) {
super(view);
view.setOnClickListener(this);
tv_android = (TextView)view.findViewById(R.id.tv_android);
img_android = (ImageView) view.findViewById(R.id.img_android);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(ClickListener clickListener) {
DataAdapter.clickListener = clickListener;
}
public interface ClickListener {
void onItemClick(int position, View v);
}
}
you are setting mAdapter = null before setting setOnItemClickListener, remove it
DataAdapter mAdapter = null ; //remove this line
adapter.setOnItemClickListener(new DataAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.d(TAG, "onItemClick position: " + position);
}
});
you are calling wrong adapter, your actual variable is adapter and you are calling it with mAdapter, that also by setting its value to ull
Try this
DataAdapter adapter = new DataAdapter(getApplicationContext(),androidVersions);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new DataAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.d(TAG, "onItemClick position: " + position);
}
});

Handle button click inside row in recyclerView

I would like to know how to handle position of the row if the adapter is changed - for example if I write something to SearchView - adapter has changed and position is different. I have done this (below), but it shows the item before changed position.
My issue is with Recycler view item click.
Could you help me with that?
Adapter
public class ContactsRecyclerAdapter extends RecyclerView.Adapter<ContactsRecyclerAdapter.BindingHolder> {
private static OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(View itemView, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
private List<Contact> mContacts;
private List<Contact> mContactsFiltered;
SearchViewFilter filter;
Context mContext;
public ContactsRecyclerAdapter(Context context, List<Contact> contact) {
this.mContext = context;
this.mContacts = contact;
this.mContactsFiltered = contact;
filter = new SearchViewFilter(mContacts, this);
}
public static class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(final View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.onItemClick(itemView, getLayoutPosition());
}
});
}
public ViewDataBinding getBinding() {
return binding;
}
}
#Override
public BindingHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_contact, parent, false);
BindingHolder holder = new BindingHolder(view);
return holder;
}
#Override
public void onBindViewHolder(BindingHolder holder, int position) {
final Contact contact = mContactsFiltered.get(position);
holder.getBinding().setVariable(BR.contact, contact);
holder.getBinding().executePendingBindings();
}
Fragment
public class ContactListFragment extends Fragment implements View.OnClickListener {
FloatingActionButton fabButton;
SearchView searchView;
RecyclerView recyclerView;
String name, number, email;
private List<Contact> mContact = new ArrayList<>();
private ContactsRecyclerAdapter mAdapter;
public static ContactListFragment newInstance() {
Bundle args = new Bundle();
ContactListFragment fragment = new ContactListFragment();
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
searchView = (SearchView) view.findViewById(R.id.search_view);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mContact = SugarRecord.listAll(Contact.class);
mAdapter = new ContactsRecyclerAdapter(getActivity(), mContact);
recyclerView.setAdapter(mAdapter);
//item click
mAdapter.setOnItemClickListener(new ContactsRecyclerAdapter.OnItemClickListener() {
#Override
public void onItemClick(View itemView, int position) {
Contact contact = SugarRecord.findById(Contact.class, (long) position + 1);
name = contact.getName();
number = contact.getNumber();
email = contact.getEmail();
showAlertDialog();
}
});
searchFilter();
return view;
}
public void sortList() {
if(mContact.size() > 0) {
if (!isSort) {
Collections.sort(mContact, new Comparator<Contact>() {
#Override
public int compare(Contact contact1, Contact contact2) {
return contact1.getName().compareToIgnoreCase(contact2.getName());
}
});
}
else {
Collections.reverse(mContact);
isSort = false;
}
}
mAdapter.notifyDataSetChanged();
Click listener does not work with a RecyclerView. use OnItemTouchListener()
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override public void onItemClick(View view, int position) {
// do whatever
}
#Override public void onLongItemClick(View view, int position) {
// do whatever
}
})
);
you have to overide onclick in BindingHolder class. Inside onclick method invoke a callback method of object passed via constructor etc
public static class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(final View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
public void onClick(View view) {
//call a callback method here
}
}
public ViewDataBinding getBinding() {
return binding;
}
}

Categories

Resources