I am trying to open another activity from a RecyclerView. I'm not understanding how to use the sendMessage() method to start the new activity. I have used the method in with another button to open a new activity all I want to do is to open up a the same activity but just with a different activity.
I have tried pluggin the sendMessage() method into the listener. I have tried using an intent.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildRecyclerView();
}
public void buildRecyclerView(){
mRecyclerView = findViewById(R.id.rvGoals);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new RVAdapter(mGoal);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new RVAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
mDrawerLayout = findViewById(R.id.nav_view);
mDrawerLayout.openDrawer(Gravity.START);
}
#Override
public void onAddClick(int position) {
sendMessage();
}
});
public void sendMessage(View view) {
Intent intent = new Intent(this,MainGoalInfo.class);
startActivityForResult(intent,1);
}
Recycler View adapter:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.GoalViewHolder> {
private List<Goals> goalsRVA;
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
void onAddClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public RVAdapter(List<Goals> goalsRVA){
this.goalsRVA=goalsRVA;
}
#Override
public int getItemCount(){
return goalsRVA.size();
}
#Override
public GoalViewHolder onCreateViewHolder(ViewGroup viewGroup,int i){
View v=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.goal_view,viewGroup,false);
GoalViewHolder gvh=new GoalViewHolder(v,mListener);
return gvh;
}
#Override
public void onBindViewHolder(GoalViewHolder goalViewHolder, int i){
goalViewHolder.goalDescriptionRV.setText(goalsRVA.get(i).getDescription());
goalViewHolder.goalDueDateRV.setText(goalsRVA.get(i).getGoalDate());
goalViewHolder.goalTitleRV.setText(goalsRVA.get(i).getGoal());
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView){
super.onAttachedToRecyclerView(recyclerView);
}
public static class GoalViewHolder extends RecyclerView.ViewHolder{
CardView cv;
TextView goalDescriptionRV;
TextView goalDueDateRV;
TextView goalTitleRV;
ImageView mAddSubGoal;
GoalViewHolder(View itemView, final OnItemClickListener listener){
super(itemView);
cv=itemView.findViewById(R.id.shit_view);
goalTitleRV=itemView.findViewById(R.id.title);
goalDueDateRV=itemView.findViewById(R.id.dueDate);
goalDescriptionRV=itemView.findViewById(R.id.description);
mAddSubGoal=itemView.findViewById(R.id.ADDSUBGOAL);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
mAddSubGoal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onAddClick(position);
}
}
}
});
}
}
}
You can perform the desired action inside setOnClickListener() method of your GoalViewHolder. You can initialize the adapter with the context from your activity:
mAdapter = new RVAdapter(mGoal, this);
Recycler View adapter:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.GoalViewHolder> {
private Context mContext;
...
public RVAdapter(List<Goals> goalsRVA, Context mContext){
this.goalsRVA=goalsRVA;
this.mContext=mContext
}
And in your GoalViewHolder:
GoalViewHolder(View itemView, final OnItemClickListener listener){
...
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext,MainGoalInfo.class);
((Activity) mContext).startActivityForResult(intent,1);
...
}
});
...
}
You can do that from inside onbindViewHolder
Send the context at the adapter constructor
Related
Listener in Android Studio RecyclerView custom adapter is returning null.
This is the Interface
private OnItemClickListener mlistener;
public interface OnItemClickListener{
void onItemClick(int position, Boolean paid);
}
public void setOnItemClickListener(OnItemClickListener listener){
mlistener = listener;
}
And this is the View Holder with the Listener. This is intended to pass a Boolean to the main activity.
public CartViewHolder(View itemView, ArrayList<Shift> shifts, OnItemClickListener listener) {
super(itemView);
paid = itemView.findViewById(R.id.due_back_paid);
containerView = itemView.findViewById(R.id.container);
paid.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position, isChecked);
}
}
}
});
containerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Shift current = (Shift)containerView.getTag();
Intent intent = new Intent(v.getContext(), ViewShiftActivity.class);
intent.putExtra("thisShift", current);
intent.putExtra("shifts", shifts);
v.getContext().startActivity(intent);
}
});
}
}
public LoadAdapter(ArrayList<Shift> shifts){
shiftList = shifts;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shift_row, parent, false);
CartViewHolder mvh = new CartViewHolder(view, shiftList, mlistener);
return mvh;
}
I have used this code in other projects and it works. I have can't seem to figure out what I am missing.
I've been asked to include the activity. The following is this code.
I have not added any code to the onItemClick here yet. waiting for the listener to work.
public class EditShiftActivity extends AppCompatActivity implements LoadAdapter.OnItemClickListener{
private ArrayList<Shift> shifts;
private RecyclerView lRecyclerView;
private LoadAdapter lAdapter;
private RecyclerView.LayoutManager lLayoutManager;
private View view;
private FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_shift);
Intent intent = getIntent();
shifts = intent.getParcelableArrayListExtra("shifts");
fab = findViewById(R.id.add_shift_edit);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(EditShiftActivity.this, AddShiftActivity.class);
intent1.putExtra("shifts", shifts);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
v.getContext().startActivity(intent1);
}
});
lRecyclerView = findViewById(R.id.shift_recycler);
lLayoutManager = new LinearLayoutManager(this);
lAdapter = new LoadAdapter(shifts);
lRecyclerView.setLayoutManager(lLayoutManager);
lRecyclerView.setAdapter(lAdapter);
}
#Override
public void onItemClick(int position, Boolean paid) {
}
}
Add below line in your code -
lAdapter = new LoadAdapter(shifts);
lAdapter.setOnItemClickListener(this);
You are retrieving the ArrayList<Shifts> from Intent. Check the size of shifts arraylist before sending to the Adapter. There is a chance that if the arraylist passed is empty then the adapter will return null and hence lRecyclerView will not be displayed.
Add this condition before passing data to adapter
//condition to check whether the arraylist is empty or not
if(!shifts.isEmpty()) {
lAdapter = new LoadAdapter(shifts);
//initialising the adapter
lRecyclerView.setAdapter(lAdapter);
}
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();
}
I've a recycler adapter where I've added setOnClickListener for items in adapter. Code is as given below:
#Override
public void onBindViewHolder(final FiltersAdapter.MyViewHolder holder, final int position) {
holder.mOrganizer.setText(filtersList.get(position));
holder.mLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Log.e("message","ONclick FIlter");
if (holder.mOrganizerCheck.isChecked()){
holder.mOrganizerCheck.setChecked(false);
}else {
holder.mOrganizerCheck.setChecked(true);
int pos = holder.getAdapterPosition();
filtersList.get(pos);
/*Bundle bundle = new Bundle();
bundle.putInt(pos, );*/
Log.d(TAG, "onClick: " +filtersList);
Log.d(TAG, "onClick of position: " +pos);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
And here is fragment code which deals with getting values from adapter to fragment.
private void initView() {
mrvFilterBySender = (RecyclerView) mFilterView.findViewById(R.id.rvFilterBySender);
mFiltersAdapter = new FiltersAdapter(getActivity(), mListOrganizer);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mrvFilterBySender.setLayoutManager(mLayoutManager);
mrvFilterBySender.setAdapter(mFiltersAdapter);
mFiltersAdapter.notifyDataSetChanged();
mrvFilterBySender.setAdapter(mFiltersAdapter);
mrvFilterBySender.setRecyclerListener(new RecyclerView.RecyclerListener() {
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
holder.getAdapterPosition();
}
});
}
I'm trying to pass pos and value having that pos from adapter to fragment. But my code isn't working. How can I fix it?
make interface to handle click event into recyclerview ..
used below code for handling click event.
onItemClickListner onItemClickListner;
public void setOnItemClickListner(RecyclerViewAdpater.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner{
void onClick(String str);//pass your object types.
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
String data=mStringList.get(position); // if you pass object of class then create that class object.
holder.textView.setText(data);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
}
then after when you bind adapter into RecyclerView call below code..
mRvData.setLayoutManager(new LinearLayoutManager(this));
mRvData.setAdapter(recyclerViewAdpater);
recyclerViewAdpater.notifyDataSetChanged();
recyclerViewAdpater.setOnItemClickListner(new RecyclerViewAdpater.onItemClickListner() {
#Override
public void onClick(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}
});
Create an interface in your adapter
public interface OnItemClickListener {
void onItemClicked(int position, Object object);
}
in your adapter call
Adapter adapter = new Adapter(context, list, new Adapter.OnItemClickListener() {
#Override
public void onItemClicked(int position, Object object) {
// Handle Object of list item here
}
});
on your adapter
private OnItemClickListener onItemClickListener; // Global scope
in constructor call:
this.onItemClickListener = onItemClickListener;
on your item clicked event :
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListener.onItemClicked(position, _list.get(position));
}
});
Please use an interface like below, pass it in the adapter's constructor, and than use it in your activity / Fragment
public MyAdapter(Context context, List<Object> data, MyAdapterListener myAdapterListener) {
this.context = context;
this.data = data;
this.myAdapterListener = myAdapterListener;
}
public interface MyAdapterListener {
void onContainerClick(View view, int position);
}
}
public class ViewHolderItem extends RecyclerView.ViewHolder implements View.OnClickListener {
public LinearLayout container;
public ImageView poster;
public ViewHolderItem(View v) {
super(v);
container = (LinearLayout) v.findViewById(R.id.container);
poster = (ImageView) v.findViewById(R.id.poster);
container =setOnClickListener(this); /// this line must include
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.container) {
if (myAdapterListener != null) {
myAdapterListener.onContainerClick(v,getAdapterPosition());
}
}
}
}
Use it like this in your fragment/Activity
mAdapter = new MyAdapter(getApplicationContext() , data, new MyAdapter.MyAdapterListener() {
#Override
public void onContainerClick(View v, int position) {
Log.d(TAG, "iconTextViewOnClick at position "+position);
}
});
mRecycler.setAdapter(mAdapter);
I thing this is work for you
Add in you adapter
public interface ClickEvent {
void clickEventItem(int position,String value);
}
ClickEvent clickevent;
public void setClickEvent(ClickEvent event) {
this.clickevent = event;
}
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clickevent.clickEventItem(position, list.get(position));
}
});
in your fragment set interface
adapter.setClickEvent(your class context);
implement ClickEvent intereface and generate #Override method
#Override
public void clickEventItem(int position,String value) {
//write your code here
}
I have this method in my activity (CreatePhotostoryActivity):
#Override
public void showEditField(Moment oldMoment, final int index){
listRecycler.setVisibility(View.GONE);
editCaption.setVisibility(View.VISIBLE);
saveCancelNavbar.setVisibility(View.VISIBLE);
momentView.setVisibility(View.GONE);
photoStoryNavbar.setVisibility(View.GONE);
header.setVisibility(View.GONE);
Picasso.with(getApplicationContext()).load(oldMoment.photoUri).into(displayPhoto);
imageCaption.setText("");
imageCaption.setText(oldMoment.caption);
backIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
}
});
saveText.setText("Save Moment");
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMoment(imageCaption.getText().toString(), index);
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", true);
startActivity(i);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeEditMoment();
Intent i = new Intent(CreatePhotostoryActivity.this, RVAdapter.class);
i.putExtra("isSaved", false);
startActivity(i);
}
});
}
In my RecyclerView adapter, showEditField is called using an interface, and it does work except that I am unable to detect whether saveButton or cancelButton was clicked. This is how it's called in the onBindViewHolder method of my RecyclerView adapter (RVAdapter):
((RecyclerView.ViewHolder) momentViewHolder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapterCallback.showEditField(moments.get(position), position);
Intent intent = ((CreatePhotostoryActivity) mContext).getIntent();
Boolean isSaved = intent.getExtras().getBoolean("isSaved");
if (isSaved) {
holder.momentCaption.setText(moments.get(position).caption);
holder.momentPlaceholder.setVisibility(View.GONE);
holder.momentCaption.setVisibility(View.VISIBLE);
} else {
holder.momentPlaceholder.setVisibility(View.VISIBLE);
holder.momentCaption.setVisibility(View.GONE);
}
notifyDataSetChanged();
});
Do note my attempt of using an intent to find out which button was clicked. It doesn't work. momentCaption remains gone and momentPlaceHolder remains visible even though saveButton was clicked. The app also crashes afterwards.
Edit: I think calling this mAdapterCallback.showEditField(moments.get(position), position); before setting the values of momentCaption and momentPlaceholder is problematic, since showEditField calls other methods (e.g. closeEditMoment() before the intent is retrieved from the adapter.
Create an interface with two methods like saveBtnClick() and cancelBtnClick().
Implement the interface in your Activity.
Implement Click listener for both the buttons in the ViewHolder of your RecyclerView and call the Appropriate methods using Inteface's Object.
//Interface
public interface ManageButtonClicks
{
void saveBtnClick();
}
//Activity
public class MainActivity extends AppCompactActivity implements ManageButtonClicks
{
ManageButtonClicks manageButtonClicks=this;
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
//Do the operations
adapter = new MyAdapter(this,adapterList,manageButtonClicks);
recyclerView.setAdapter(adapter);
}
void saveBtnClick()
{
Toast.makeText(this,"Clicked",Toast.LENGTH_SHORT).show();
}
}
//Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
ManageButtonClicks manageButtonClicks;
public MyAdapter(Context context, List< ModelClass > data, ManageButtonClicks manageButtonClicks)
{
inflater = LayoutInflater.from(context);
this.mDataList = data;
this.ctx = context;
util = new Util(ctx);
this.manageButtonClicks = manageButtonClicks;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
ViewGroup nonPrimeRow = (ViewGroup) inflater.inflate(R.layout.rowlayout, parent, false);
MyViewHolder_NON_PRIME holderNonPrime = new MyViewHolder_NON_PRIME(nonPrimeRow);
return holderNonPrime;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position)
{
ModelClass current = mDataList.get(position);
MyViewHolder_NON_PRIME holder_not_prime = (MyViewHolder_NON_PRIME) holder;
holder_not_prime.setdata(current);
}
class MyViewHolder extends RecyclerView.ViewHolder
{
public MyViewHolder(View itemView)
{
super(itemView);
}
}
public class MyViewHolder_NON_PRIME extends MyViewHolder
{
private Button btnSave;
public MyViewHolder_NON_PRIME(View view)
{
super(view);
btnSave = (MonteButton) view.findViewById(R.id.btnSave);
}
public void setdata(final ModelClass current)
{
btnSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
manageButtonClicks.saveBtnClick();
}
});
}
}
You have a global variable inside recyclerView adapter:
RecyclerViewAdapter {
private boolean isSaveButtonClicked = false;
private boolean isCancelButtonClicked = false;
public void saveButtonClicked(){
isSaveButtonClicked = true;
}}
public void cancelButtonClicked(){
isCancelButtonClicked = true;
}}
When your activity call onclickListeners , you will notice your adapter.
CreatePhotostoryActivity(){
private RecyclerView adapter;
onSaveButtonClicked(){
adapter.saveButtonClicked();
}
onCancelButtonClicked(){
adapter.cancelButtonClicked();
}
}
I have created a recyclerView in a Fragment, i also implement the onItemClickListener in the adapter.
now i need to give the click the action in the recyclerView in the Fragment but i can't do it.
Hope you can help me to figure out it. I appreciate it.
First this is the Adapter:
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
public TextView textName;
public TextView textAddress;
public ImageView imageView;
private Place place;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
textName = (TextView) itemLayoutView.findViewById(R.id.placeName);
textAddress = (TextView) itemLayoutView.findViewById(R.id.placeAddress);
imageView = (ImageView) itemLayoutView.findViewById(R.id.imagePlace);
}
public void bind(Place place) {
this.place = place;
textName.setText(place.getName());
textAddress.setText(place.getAdress());
}
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
#Override
public boolean onLongClick(View v) {
clickListener.onItemLongClick(getAdapterPosition(), v);
return false;
}
public void setOnItemClickListener(ClickListener clickListener) {
PlaceAdapter.clickListener = clickListener;
}
public interface ClickListener {
void onItemClick(int position, View v);
void onItemLongClick(int position, View v);
Place sendToMap();
}
}
then i have the Fragment:
public class FragmentNearMe extends Fragment
implements View.OnClickListener {
public static final String ARG_PAGE = "ARG_PAGE";
public static final String SEARCH_RESULT_ACTION="SEARCH_RESULT_ACTION";
private int aroundMe;
private PlaceAdapter adapter;
private LocationManager locationManager;
private SearchBrodcastReciver searchBrodcastReciver;
private EditText searchFild;
private LatLng latLng;
private ImageView iconPlace;
private Context context;
public void setLatLng(LatLng latLng) {
if (this.latLng == null) {
getView().findViewById(R.id.location_warning).setVisibility(View.GONE);
searchFild.setVisibility(View.VISIBLE);
}
this.latLng = latLng;
}
public static FragmentNearMe newInstance(int around) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, around);
FragmentNearMe fragment = new FragmentNearMe();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
aroundMe = getArguments().getInt(ARG_PAGE);
searchBrodcastReciver=new SearchBrodcastReciver();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_near_me, container, false);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView listPlaces = (RecyclerView) view.findViewById(R.id.placesList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
adapter = new PlaceAdapter(new ArrayList<Place>());
listPlaces.setLayoutManager(layoutManager);
listPlaces.setAdapter(adapter);
searchFild= (EditText) view.findViewById(R.id.textSearch);
ImageButton imageButton= (ImageButton) view.findViewById(R.id.searchbtn);
imageButton.setOnClickListener(this);
}
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(searchBrodcastReciver, new IntentFilter(SEARCH_RESULT_ACTION));
}
#Override
public void onPause() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(searchBrodcastReciver);
super.onPause();
}
#Override
public void onClick(View v) {
String placeName= searchFild.getText().toString();
if(placeName != null) {
Intent intent = new Intent(getActivity(), MyIntentService.class);
intent.putExtra(MyIntentService.KEY_PLACE, placeName);
intent.putExtra(MyIntentService.KEY_RADIUS, 5);
intent.putExtra(MyIntentService.KEY_LOCATION, latLng);
getActivity().startService(intent);
}else {
Toast.makeText(getContext() , "place not exsist" , Toast.LENGTH_SHORT).show();
}
}
public class SearchBrodcastReciver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(SEARCH_RESULT_ACTION)){
PlaceLogic placeLogic= new PlaceLogic(getActivity());
adapter.setPlaces(placeLogic.getAllPlaces());
}
}
}
}
copy this inside you Adapter
public interface OnClickListner {
void setOnItemClick(int postion, View view);
}
then create an instance OnClickListner onClickListner ;
then create a setter public void setOnClickListner(OnClickListner onClickListner ) {
this.onClickListner = onClickListner ;
}
now in OnBind
holder.myview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClickListner .setOnItemClick(position,view);
}
});
then in Your fragment
paste these
adapter.setOnClickListner(this);
then implement method and perform action
Add onclick on the layout itemLayoutView it will work.
This is the click listener
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
public static class RecyclerItemListner implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private AtInfamaCenter.ClickListener clickListener;
public RecyclerItemListner(Context context, final RecyclerView recyclerView, final AtInfamaCenter.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
Then use it this way in the onActivityCreated method
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
recyclerView.addOnItemTouchListener(new MyActivity.RecyclerItemListner(getActivity(), recyclerView, new MyActivity.ClickListener() {
#Override
public void onClick(View view, int position) {
//Code when item is clicked
}
#Override
public void onLongClick(View view, final int position) {
// code when item is long clicked
}
}));
I hope this helps. Happy coding