Save, Share & Favourite Imageview in recyclerview - android

this codes contains a share button, download button, and a favourate button.
till now its working properly with favourate button, if i remove onClick method from ViewHolder.
I want to implement share/save button onClick share/download the Image in the ImageView in recyclerview.
Please ignore gramatical mistakes
This is my cardFragment Class.
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CardFragment extends Fragment {
ArrayList<WonderModel> listitems = new ArrayList<>();
RecyclerView MyRecyclerView;
String Wonders[] = {"Chichen Itza","Christ the Redeemer","Great Wall of China","Machu Picchu","Petra","Taj Mahal","Colosseum"};
int Images[] = {R.drawable.chichen_itza,R.drawable.christ_the_redeemer,R.drawable.great_wall_of_china,R.drawable.machu_picchu,R.drawable.petra,R.drawable.taj_mahal,R.drawable.colosseum};
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeList();
getActivity().setTitle("7 Wonders of the Modern World");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_card, container, false);
MyRecyclerView = (RecyclerView) view.findViewById(R.id.cardView);
MyRecyclerView.setHasFixedSize(true);
LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
if (listitems.size() > 0 & MyRecyclerView != null) {
MyRecyclerView.setAdapter(new MyAdapter(listitems));
}
MyRecyclerView.setLayoutManager(MyLayoutManager);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private ArrayList<WonderModel> list;
public MyAdapter(ArrayList<WonderModel> Data) {
list = Data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_items, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.titleTextView.setText(list.get(position).getCardName());
holder.coverImageView.setImageResource(list.get(position).getImageResourceId());
holder.coverImageView.setTag(list.get(position).getImageResourceId());
holder.likeImageView.setTag(R.drawable.ic_like);
}
#Override
public int getItemCount() {
return list.size();
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView;
public ImageView coverImageView;
public ImageView likeImageView;
public ImageView shareImageView;
public MyViewHolder(View v) {
super(v);
titleTextView = (TextView) v.findViewById(R.id.titleTextView);
coverImageView = (ImageView) v.findViewById(R.id.coverImageView);
likeImageView = (ImageView) v.findViewById(R.id.likeImageView);
shareImageView = (ImageView) v.findViewById(R.id.shareImageView);
likeImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = (int)likeImageView.getTag();
if( id == R.drawable.ic_like){
likeImageView.setTag(R.drawable.ic_liked);
likeImageView.setImageResource(R.drawable.ic_liked);
Toast.makeText(getActivity(),titleTextView.getText()+" added to favourites",Toast.LENGTH_SHORT).show();
}else{
likeImageView.setTag(R.drawable.ic_like);
likeImageView.setImageResource(R.drawable.ic_like);
Toast.makeText(getActivity(),titleTextView.getText()+" removed from favourites",Toast.LENGTH_SHORT).show();
}
}
});
shareImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" + getResources().getResourcePackageName(coverImageView.getId())
+ '/' + "drawable" + '/' + getResources().getResourceEntryName((int)coverImageView.getTag()));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,imageUri);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
}
});
}
}
public void initializeList() {
listitems.clear();
for(int i =0;i<7;i++){
WonderModel item = new WonderModel();
item.setCardName(Wonders[i]);
item.setImageResourceId(Images[i]);
item.setIsfav(0);
item.setIsturned(0);
listitems.add(item);
}
}
}
Here is MainActivity.Java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new CardFragment();
;
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}

Create your ViewHolder Constructor Like this
public MyViewHolder(View v,Activity activity) {
super(v);
this.activity = activity
/////Remaining code
Now you able to get the activity context in your viewholder class.
Hope it will helps you!!

Related

Opening a new Activity from a RecyclerView with Firebase data

I'm creating a TripAdvisor clone app that gets data from a Firebase database and shows data from it. I want to add a listener to the RecyclerView that opens a new Activity called locationInDetailActivity that shows informations about the picked element. Here are the codes for the MainActivity and the RecyclerView adapter.
MainActivity.java
package com.example.progettocv19ingsw;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
private Button to_advanced_filters;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private DatabaseReference reference;
private RecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
to_advanced_filters = (Button) findViewById(R.id.advancedFilters);
recyclerView = findViewById(R.id.locationRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
to_advanced_filters.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openAdvancedFilterActivity();
}
});
reference = FirebaseDatabase.getInstance().getReference();
FirebaseRecyclerOptions<locationClass> options = new FirebaseRecyclerOptions.Builder<locationClass>().setQuery(FirebaseDatabase.getInstance().getReference().child("locations"), locationClass.class).build();
adapter = new RecyclerViewAdapter(options);
recyclerView.setAdapter(adapter);
}
public void openAdvancedFilterActivity(){
Intent open = new Intent(this, AdvancedFilters.class);
startActivity(open);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
RecyclerViewAdapter.java
package com.example.progettocv19ingsw;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
public class RecyclerViewAdapter extends FirebaseRecyclerAdapter<locationClass, RecyclerViewAdapter.myViewHolder> {
private static final String TAG = "RecyclerView";
public RecyclerViewAdapter(#NonNull FirebaseRecyclerOptions options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myViewHolder viewHolder, int i, #NonNull locationClass location) {
viewHolder.locationName.setText(location.getLocationName());
viewHolder.locationType.setText(location.getLocationType());
Glide.with(viewHolder.locationImage.getContext()).load(location.getLocationPic()).into(viewHolder.locationImage);
viewHolder.reviewNumber.setText(String.valueOf(location.getReviewNumber()));
viewHolder.averageRatingBar.setRating(location.getAverageRating());
viewHolder.averageRatingBar.setStepSize(location.getAverageRating());
}
#Override
public int getItemCount() {
return super.getItemCount();
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.location_recyclerrow, parent, false);
return new myViewHolder(v);
}
class myViewHolder extends RecyclerView.ViewHolder {
ImageView locationImage;
TextView locationName;
TextView locationType;
RatingBar averageRatingBar;
TextView reviewNumber;
Context context;
public myViewHolder(#NonNull View itemView) {
super(itemView);
locationImage = (ImageView) itemView.findViewById(R.id.locationPicture);
locationName = (TextView) itemView.findViewById(R.id.locationName);
locationType = (TextView) itemView.findViewById(R.id.locationType);
reviewNumber = (TextView) itemView.findViewById(R.id.reviewNumber);
averageRatingBar = (RatingBar) itemView.findViewById(R.id.averageRating);
}
}
}
locationInDetailActivity.java
package com.example.progettocv19ingsw;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class locationInDetailActivity extends AppCompatActivity {
private static final String TAG = "locationDetailActivity";
private Button toReviews;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_data);
Log.d(TAG, "onCreate: Started");
toReviews.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
openReviewActivity();
}
});
}
private void openReviewActivity() {
Intent intent = new Intent(this, reviewActivity.class);
}
}
I have tried adding an OnClick listener, but it either gives me "cannot resolve method" or NullPointerException() errors. What do I do?
Colin Degen is right, but you can do something more generic.
Create a interface for the clicks event:
public interface IClickListener {
void onItemClick(int position, View view);
void onItemLongClick(int position, View view);
}
Create a recycler view adapter to suit your needs:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private IClickListener clickListener;
private List<String> models;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener, View.OnClickListener {
public TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
clickListener.onItemClick(getAdapterPosition(), view);
}
#Override
public boolean onLongClick(View view) {
clickListener.onItemLongClick(getAdapterPosition(), view);
return false;
}
}
public RecyclerViewAdapter(List<String> models) {
this.models = models;
}
public void setOnItemClickListener(IClickListener clickListener) {
this.clickListener = clickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final String model = models.get(position);
TextView textView = holder.textView;
textView.setText(model);
}
#Override
public int getItemCount() {
return models.size();
}}
Then, when you want to use your recycler view you can do something like this:
ArrayList<String> dataSource = new ArrayList<String>()
// Add some data to the dataSource
RecyclerViewAdapter adapter = new RecyclerViewAdapter(dataSource);
adapter.setOnItemClickListener(new IClickListener() {
#Override
public void onItemClick(int position, View view) {
String model = dataSource.get(position);
// Do stuff with your model like passing data to the next activity
}
});
You have to define an OnClickListener for each element in your RecyclerView.
private final OnClickListener mOnClickListener = new MyOnClickListener(){
#Override
public void onClick(final View view) {
int itemPosition = mRecyclerView.getChildLayoutPosition(view);
YourItem item = mList.get(itemPosition);
//Do stuff and start your activity
}
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.location_recyclerrow, parent, false);
view.setOnClickListener(mOnClickListener);
return new myViewHolder(v);
}
And then you pass your RecyclerView instance to the constructor of your adapter
private RecyclerView mRecyclerView;
public RecyclerViewAdapter(#NonNull FirebaseRecyclerOptions options, RecyclerView rV) {
super(options);
mRecyclerView = rV;
}

passing string variable from recyclerview to fragment

i try to get the name of the movies which are in recycler view n store in variable 'name' but how do i pass in to dictionary fragment n set it on definitionn(edittext). i tried with this code but it shows empty
i try to get the name of the movies which are in recycler view n store in variable 'name' but how do i pass in to dictionary fragment n set it on definitionn(edittext). i tried with this code but it shows empty
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
// item of recyclerview was not visible until included
app:layoutManager="android.support.v7.widget.LinearLayoutManager">
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerAdapter recyclerAdapter;
List<String> moviesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moviesList = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
recyclerAdapter = new RecyclerAdapter(moviesList);
recyclerView.setAdapter(recyclerAdapter);
DividerItemDecoration dividerItemDecoration = new
DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(dividerItemDecoration);
moviesList.add("IronMan");
moviesList.add("The Incredible Hulk");
moviesList.add("Iron Man 2");
moviesList.add("Thor");
moviesList.add("Captain America: The First Avenger");
moviesList.add("The Avengers");
moviesList.add("Iron Man 3");
moviesList.add("Thor: The Dark World");
moviesList.add("Captain America: The Winter Soldier");
moviesList.add("Guardians of the Galaxy");
moviesList.add("Avengers: Age of Ultron");
moviesList.add("Ant-Man");
moviesList.add("Captain America: Civil War");
moviesList.add("Doctor Strange");
moviesList.add("Guardians of the Galaxy Vol. 2");
moviesList.add("Spider-Man: Homecoming");
moviesList.add("Thor: Ragnarok");
moviesList.add("Black Panther");
moviesList.add("Avengers: Infinity War");
moviesList.add("Ant-Man and the Wasp");
moviesList.add("Captain Marvel");
moviesList.add("Avengers: Endgame");
moviesList.add("Spider-Man: Far From Home");
}
}
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
String name="";
private static final String TAG = "RecyclerAdapter";
List<String> moviesList;
public RecyclerAdapter(List<String> moviesList) {
this.moviesList = moviesList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
LayoutInflater layoutInflater =
LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.row_item, parent,
false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int
position) {
holder.rowCountTextView.setText(String.valueOf(position));
holder.textView.setText(moviesList.get(position));
}
#Override
public int getItemCount() {
return moviesList.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
ImageView imageView;
TextView textView, rowCountTextView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
textView = itemView.findViewById(R.id.textView);
rowCountTextView =
itemView.findViewById(R.id.rowCountTextView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(new
View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
moviesList.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
return true;
}
});
}
#Override
public void onClick(View view) {
name=moviesList.get(getAdapterPosition()).toString();
AppCompatActivity activity=(AppCompatActivity)
view.getContext();
Fragment myfragment = new Dictionary();
activity.getSupportFragmentManager().beginTransaction().
replace(R.id.activitymain,myfragment).addToBackStack(null).commit();
}
}
}
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class Dictionary extends Fragment {
public EditText definitionnn;
public Dictionary() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dictionary, container, false);
definitionnn = (EditText) v.findViewById(R.id.definition);
RecyclerAdapter recycle = new RecyclerAdapter(null);
String word = recycle.name;
return v;
}
#Override
public void onStart() {
super.onStart();
RecyclerAdapter recycle = new RecyclerAdapter(null);
String word = recycle.name;
definitionnn.setText(word);
}
}
The problem is that in your OnClick() Method you create and add the new Dictionary Fragment without passing the value you want. Something like this would be your solution.
In your RecyclerAdapter class:
Bundle bundle = new Bundle();
bundle.putString(yourVariable, "word");
Fragment fragment = new Dictionary();
fragobj.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().
replace(R.id.activitymain,fragment).addToBackStack(null).commit();
And in your Dictionary Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dictionary, container, false);
String word = getArguments().getString("word");
definitionnn = (EditText) v.findViewById(R.id.definition)
definitionnn.setText(word);
return v;
}

how to add clicklistener for each item

I have an Array list here,
I want each of them when clicked, they will do a specific function or intent an activity.
Currently: each item contains, ImageButton and a Textview in a list.
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class MyBottomSheetDialogFragment extends BottomSheetDialogFragment {
String mString;
private RecyclerView mRecyclerView;
private VerticalListAdapter mVerticalListAdapter;
static MyBottomSheetDialogFragment newInstance(String string) {
MyBottomSheetDialogFragment f = new MyBottomSheetDialogFragment();
Bundle args = new Bundle();
args.putString("string", string);
f.setArguments(args);
return f;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mString = getArguments().getString("string");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.bottom_sheet_modal_list, container, false);
mRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
List<Model> list = new ArrayList<Model>();
list.add(new Model(R.drawable.a1, "Call"));
list.add(new Model(R.drawable.a2, "Chat"));
list.add(new Model(R.drawable.a3, "Android"));
list.add(new Model(R.drawable.a4, "Location"));
list.add(new Model(R.drawable.a5, "Call"));
list.add(new Model(R.drawable.a6, "Chat"));
list.add(new Model(R.drawable.a7, "Android"));
mVerticalListAdapter = new VerticalListAdapter(getContext(), list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(mVerticalListAdapter);
}
I can provide additional XML , Java codes of the project that is relatively connected to this code, Please leave a comment for clarification.
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.List;
public class VerticalListAdapter extends RecyclerView.Adapter<VerticalListAdapter.MyViewHolder>{
private Context mContext;
private List<Model> mModelList;
public VerticalListAdapter(Context context, List<Model> list) {
this.mContext = context;
this.mModelList = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.modal_list_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.txtView.setText(mModelList.get(position).getName());
holder.imgView.setImageDrawable(mContext.getResources().getDrawable(mModelList.get(position).getImgId()));
}
#Override
public int getItemCount() {
return mModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView txtView;
public ImageButton imgView;
public MyViewHolder(View view) {
super(view);
txtView = (TextView) view.findViewById(R.id.txtView);
imgView = (ImageButton) view.findViewById(R.id.imgView);
}
}
}
What you need to do is to implement the OnClickListener to your Holder class and add id to your LinearLayout in modal_list_item.xml so you can click on the entire layout not only its views (if I understand you correctly) and eventually set the onClickListener.
When you do this, you will need to implement the onClick method. For inspiration see the code below:
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtView;
public ImageButton imgView;
private LinearLayout linearLayout;
public MyViewHolder(View view) {
super(view);
txtView = (TextView) view.findViewById(R.id.txtView);
imgView = (ImageButton) view.findViewById(R.id.imgView);
linearLayout = (LinearLayout) view.findViewById(R.id.linear_l);
linearLayout.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.i("RecyclerView Item", String.valueOf(getLayoutPosition()));
mModelList.remove(getLayoutPosition());
notifyDataSetChanged();
}
}

RecyclerView giving errors

Hi i am new to android project so i am trying to use recycler view. but it is not working. i keep getting errors # this line " RecyclerAdapter adapter = new RecyclerAdapter(this, getData());" it says RecyclerAdapter (android.content.context, List) in RecyclerAdapter cannot be applied to my package class please help
statement.java
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import nnnnn.R;
import nnnnnn.RecyclerAdapter;
import nnnnnnnnnnnnn.Landscape;
public class Statements extends Fragment {
Toolbar toolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.statements,container,false);
toolbar = (Toolbar) v.findViewById(R.id.toolbar);
toolbar.setTitle("Statements");
toolbar.inflateMenu(R.menu.menu_main);
setUpRecyclerView();
return v;}
private void setUpRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
RecyclerAdapter adapter = new RecyclerAdapter(this.getActivity(),Landscape.getData());
recyclerView.setAdapter(adapter);
final LinearLayoutManager mLinearLayoutManagerVertical = new LinearLayoutManager(this.getActivity()); // (Context context, int spanCount)
mLinearLayoutManagerVertical.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLinearLayoutManagerVertical);
recyclerView.setItemAnimator(new DefaultItemAnimator()); // Even if we dont use it then also our items shows default animation. #Check Docs
}
}
RecyclerAdapter code is below
RecyclerAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import xx.xx.xx.xx.xx.R;
import xx.xx.xx.xx.model.Landscape;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private static final String TAG = RecyclerAdapter.class.getSimpleName();
private List<Landscape> mDataList;
private LayoutInflater inflater;
public RecyclerAdapter(Context context, List<Landscape> data) {
this.mDataList = data;
this.inflater = LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder");
View view = inflater.inflate(R.layout.statementlist, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.i(TAG, "onBindViewHolder" + position);
Landscape current = mDataList.get(position);
holder.setData(current, position);
holder.setListeners();
}
#Override
public int getItemCount() {
return mDataList.size();
}
public void removeItem(int position) {
mDataList.remove(position);
notifyItemRemoved(position);
// notifyItemRangeChanged(position, mDataList.size());
// notifyDataSetChanged();
}
public void addItem(int position, Landscape landscape) {
mDataList.add(position, landscape);
notifyItemInserted(position);
// notifyItemRangeChanged(position, mDataList.size());
// notifyDataSetChanged();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
ImageView imgThumb, imgDelete, imgAdd;
int position;
Landscape current;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tvTitle);
imgThumb = (ImageView) itemView.findViewById(R.id.img_row);
imgDelete = (ImageView) itemView.findViewById(R.id.img_row_delete);
imgAdd = (ImageView) itemView.findViewById(R.id.img_row_add);
}
public void setData(Landscape current, int position) {
this.title.setText(current.getTitle());
imgThumb.setImageResource(current.getImageID());
this.position = position;
this.current = current;
}
public void setListeners() {
imgDelete.setOnClickListener(MyViewHolder.this);
imgAdd.setOnClickListener(MyViewHolder.this);
imgThumb.setOnClickListener(MyViewHolder.this);
}
#Override
public void onClick(View v) {
// Log.i("onClick before operation", position + " " + mDataList.size());
switch (v.getId()) {
case R.id.img_row_delete:
removeItem(position);
break;
case R.id.img_row_add:
addItem(position, current);
break;
}
// Log.i("onClick after operation", mDataList.size() + " \n\n" + mDataList.toString());
}
}
}
You're passing in "this" for the first argument to RecyclerAdapter. "this" being a Fragment class. The Fragment class does not extend from Context, so it cannot be used as such.
Try "this.getActivity()". This may result in null, so ideally put this within the Fragment subclass's "onActivityCreated" method (instead of the "onCreateView" method)
You need to override OnActivitycreated in order to call getActivity. Call setUpRecyclerView in OnActivitycreated and add getActivity. before findViewById and it will work

Can't start Activity from Recycler Adapter

I tried to find solution, but my weak programming skills didn't help me to solve problem.
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {
List<HeroItem> mItems;
Context mContext;
MyOnItemClickListener listener;
public GridAdapter(Context context) {
super();
this.mContext = context;
mItems = new ArrayList<HeroItem>();
HeroItem species = new HeroItem();
//species.setName("Amur Leopard");
species.setThumbnail(R.drawable.test1);
mItems.add(species);
species = new HeroItem();
//species.setName("Black Rhino");
species.setThumbnail(R.drawable.test2);
mItems.add(species);
species = new HeroItem();
//species.setName("Orangutan");
species.setThumbnail(R.drawable.test3);
mItems.add(species);
species = new HeroItem();
//species.setName("Sea Lions");
species.setThumbnail(R.drawable.test4);
mItems.add(species);
species = new HeroItem();
//species.setName("Indian Elephant");
species.setThumbnail(R.drawable.test5);
mItems.add(species);
species = new HeroItem();
// species.setName("Giant Panda");
species.setThumbnail(R.drawable.test6);
mItems.add(species);
species = new HeroItem();
//species.setName("Snow Leopard");
species.setThumbnail(R.drawable.test1);
mItems.add(species);
species = new HeroItem();
//species.setName("Dolphin");
species.setThumbnail(R.drawable.test1);
mItems.add(species);
}
#Override
public GridAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.grid_item, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
HeroItem nature = mItems.get(position);
//viewHolder.tvspecies.setText(nature.getName());
//viewHolder.imgThumbnail.setImageResource(nature.getThumbnail());
Picasso.with(mContext)
.load(nature.getThumbnail())
.into(viewHolder.imgThumbnail);
viewHolder.setListener(new MyOnItemClickListener() {
#Override
public void MyOnClickListener(int position) {
//Log.d("Click","Position: " + position);
switch (position) {
case 0:
Intent intent = new Intent(mContext, Wolverine.class);
mContext.startActivity(intent);
break;
}
}
});
}
#Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView imgThumbnail;
//public TextView tvspecies;
public ViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView) itemView.findViewById(R.id.photoView);
//tvspecies = (TextView)itemView.findViewById(R.id.tv_species);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listener.MyOnClickListener(getAdapterPosition());
}
public void setListener(MyOnItemClickListener onItemClick) {
listener = onItemClick;
}
}
public interface MyOnItemClickListener {
void MyOnClickListener(int position);
}
}
So, I wrote my own listener that needs position of the item, as you can see. I have no problems with showing position in logs Log.d("Click","Position: " + position); , but I still can't to start new Activity.
And here is code of my fragment Activity that uses adapter
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
public class TabHero extends Fragment {
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
int widthRecycler,widthScreen,padding;
public static TabHero newInstance() {
Bundle args = new Bundle();
TabHero fragment = new TabHero();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_hero, container, false);
// Calling the RecyclerView
mRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
// The number of Columns
mLayoutManager = new GridLayoutManager(getActivity(), 2);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new GridAdapter(getContext());
mRecyclerView.setAdapter(mAdapter);
return v;
}
}
What I do wrong?
itemViewHolder.CategoryItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(context, SubcatogaryActivity.class);
i.putExtra("id",Integer.toString(received_dataList.get(position).getId()));
context.startActivity(i);
}
});

Categories

Resources