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
Related
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;
}
I am trying to call a custom dialog fragment i have created from a dialog fragment adapter that extends a recyclerView. I'm using the latest android studio with androidx. the following code is for the Custom dialog Adapter
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import tino.varconn.com.instantecocash.R;
public class DialogSendMoneyFirst extends DialogFragment {
#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.fragment_send_money_first, container, false);
// Do all the stuff to initialize your custom view
return v;
}
The following code i am trying to use to call the dialog fragment
package tino.varconn.com.instantecocash;
import android.content.Context;
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 androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import tino.varconn.com.instantecocash.dialogs.DialogSendMoneyFirst;
public class EcocashAdapter extends
RecyclerView.Adapter<EcocashAdapter.MyViewHolder> {
private List<EcocashModel> itemList;
Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView img;
public CardView cardView;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.listtext);
img = (ImageView) view.findViewById(R.id.logo);
cardView = (CardView) view.findViewById(R.id.cardView);
}
}
public EcocashAdapter(List<EcocashModel> itemList) {
this.itemList = itemList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
EcocashModel ecocashModel = itemList.get(position);
holder.title.setText(ecocashModel.getName());
holder.img.setImageResource(ecocashModel.getImage());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 0){
Toast.makeText(v.getContext(), "Send Money", Toast.LENGTH_SHORT).show();
DialogSendMoneyFirst dialog = new DialogSendMoneyFirst();
dialog.show(((AppCompatActivity)context).getFragmentManager(), "MyCustomDialog");
}
if (position == 1){
Toast.makeText(v.getContext(), "Pay Merchant", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public int getItemCount() {
return itemList.size();
}
And this is the error :
Attempt to invoke virtual method 'android.app.FragmentManagerandroidx.appcompat.app.AppCompatActivity.getFragmentManager()' on a null object reference
Try this
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_list_row, parent, false);
context = itemView.getContext()
return new MyViewHolder(itemView);
}
If not work :
1.Check your activity is AppCompact or not.
2.If you are calling your adapter from fragment then use getChildFragmentManager()
If you are calling your adapter from Activity then use getSupportFragmentManager()
Your context is null
Try this:
getActivity().getSupportFragmentManager()
instead of:
(AppCompatActivity)context).getFragmentManager()
If your context arrives from Fragment, then you have to use below: [cast context to FragmentActivity]
dialog.show(((FragmentActivity) mContext).getSupportFragmentManager(), tag);
Suppose I have a scrolling RecyclerView (where images scrolling Horizontally) after clicking any of images it will appear below the recyclerView.
Main Activity:
package com.aariyan.testm;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;`enter code here`
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;`enter code here`
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
//implements BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener
private SliderLayout mDemoSlider;
private ImageView imageView;
private String selectDrinkCategory;
private String drinks = "drinks";
//String i = "0";
int j;
RecyclerViewAdapter recyclerViewAdapter;
private int[] images = {R.drawable.a,
R.drawable.bb,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.d_2_1,
R.drawable.d_2_2,
R.drawable.d_2_3,
R.drawable.d_2_4
};
private ArrayList<Integer> inputImages = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get Intent
Intent intent = getIntent();
if (getIntent() != null) {
selectDrinkCategory = intent.getStringExtra("drinks");
}
initUI();
initBitmapImages();
initRecyclerView();
Toast.makeText(this, "J: "+j, Toast.LENGTH_SHORT).show();
}
private void initRecyclerView() {
LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(manager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(inputImages, this);
Toast.makeText(this, " Main Value j : " + adapter.index, Toast.LENGTH_SHORT).show();
imageView.setImageResource(images[j]);
recyclerView.setAdapter(adapter);
}
private void initBitmapImages() {
for (int i = 0; i < images.length; i++) {
// inputImages.add(String.valueOf(images[i]));
inputImages.add(images[i]);
}
}
private void initUI() {
//mDemoSlider = (SliderLayout) findViewById(R.id.slider);
imageView = findViewById(R.id.viewSingleImages);
//imageView.setImageResource((images[0]));
}
#Override
protected void onStop() {
// To prevent a memory leak on rotation, make sure to call stopAutoCycle() on the slider before activity or fragment is destroyed
super.onStop();
}
}
RecyclerView:
I have a scrolling RecyclerView (where images scrolling Horizontally) after clicking any of images it will appear below the
package com.aariyan.testm;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
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.Toast;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<Integer> totalImages = new ArrayList<>();
private Context context;
//MainActivity mainActivity;
int index = 0;
public RecyclerViewAdapter(ArrayList<Integer> totalImages, Context context) {
this.totalImages = totalImages;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.images, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
//index = 0;
Glide.with(context).asBitmap().load(totalImages.get(i)).into(viewHolder.singleImages);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isClicked) {
Toast.makeText(context, "TotalImages : "+totalImages.get(i), Toast.LENGTH_SHORT).show();
index = totalImages.get(i);
}
});
// viewHolder.singleImages.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Toast.makeText(context, "" + viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
// //viewHolder.imageView.setImageResource(totalImages.get(viewHolder.getAdapterPosition()));
// //index = viewHolder.getAdapterPosition();
// index = i;
// Toast.makeText(context, "Index : " + index, Toast.LENGTH_SHORT).show();
// }
// });
}
#Override
public int getItemCount() {
return totalImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView singleImages;
private ItemClickListener itemClickListener;
public ViewHolder(#NonNull View itemView) {
super(itemView);
singleImages = itemView.findViewById(R.id.imagesViewOnScroll);
itemView.setOnClickListener(this);
}
public void setItemClickListener (ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v,getAdapterPosition(),false);
}
}
}
activity_main.xml : just have a recyclerView and image View
and images.xml : only a image view to set on RecyclerView
for get clicked item of recyckerview you have to use interface.
here is code sample:
first of all make one interface like below :
public interface ImageClickListener {
void onImageClick(String path);
}
now in your activity, make adapter's object like this
RecyclerViewAdapter adapter = new RecyclerViewAdapter(inputImages, this, new ImageClickListener() {
#Override
public void onImageClick(String path) {
Glide.with(context).load(path).into(imageView);
}
});
now create your adapter and make a constructor like this
public RecyclerViewAdapter(ArrayList<Integer> totalImages, Context context, ImageClickListener imageClickListener) {
this.totalImages = totalImages;
this.context = context;
this.imageClickListener = imageClickListener;
}
now you have an instance of interface in which you have one method, named onImageClick() in which you will pass the path of clicked image.
now on click of image do code like this:
viewHolder.singleImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageClickListener.onImageClick(totalImages.get(viewHolder.getAdapterPosition()));
}
});
now your method of interface will call & it will execute activity's image view to set the given path.
Enjoy codding :)
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!!
hi i have a recyclerview with GridLayoutManager that have 3 cols but in the first row just shows 2 items like this :
where i was wrong in this codes :
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
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 com.github.florent37.materialviewpager.MaterialViewPagerHelper;
import com.github.florent37.materialviewpager.adapter.RecyclerViewMaterialAdapter;
import java.util.ArrayList;
import java.util.List;
public class Main_Recycle6 extends Fragment {
private RecyclerView recyclerView;
private Main_Recycle_Adapter2 movieRecyclerviewAdapter;
private List<Main> movies;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.main_grid4, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
movies = new ArrayList<>();
recyclerView = (RecyclerView) getView().findViewById(R.id.Recycle1);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// recyclerView.setNestedScrollingEnabled(false);
RecyclerView.LayoutManager layoutManager;
layoutManager = new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(layoutManager);
movies = getData();
movieRecyclerviewAdapter = new Main_Recycle_Adapter2 (getActivity(), movies);
recyclerView.setAdapter(movieRecyclerviewAdapter);
RecyclerViewMaterialAdapter movieRecyclerviewAdapterMaterial = new RecyclerViewMaterialAdapter(movieRecyclerviewAdapter);
// 4. set adapter
recyclerView.setAdapter(movieRecyclerviewAdapterMaterial);
//5. Register the recyclerview to MaterialViewPager
MaterialViewPagerHelper.registerRecyclerView(getActivity(), recyclerView, null);
}
public static Main_Recycle newInstance() {
return new Main_Recycle();
}
private List<Main> getData() {
List<Main> movies = new ArrayList<>();
String names[] = { "آزمون 1",
"آزمون 2",
.....
};
String logos[] = {"i1",
"i2",
.....
};
for (int i = 0; i < names.length; i++) {
Main newMovie = new Main(names[i], logos[i]);
movies.add(newMovie);
}
return movies;
}
adapter :
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.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class Main_Recycle_Adapter2 extends RecyclerView.Adapter<Main_Recycle_Adapter2.MovieViewHolder> {
List<Main> movies = Collections.emptyList();
LayoutInflater layoutInflater;
Context context;
public Main_Recycle_Adapter2(Context context, List<Main> movies){
this.context = context;
layoutInflater = LayoutInflater.from(context);
this.movies = movies;
}
//;;;;;;;;;;;;;;
#Override
public int getItemCount() {
return movies.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType )
{
View row;
row = layoutInflater.inflate(R.layout.gridview_custom_layout, parent, false);
MovieViewHolder holder = new MovieViewHolder(row);
return holder;
}
#Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Main thisMovie = movies.get(position);
holder.tozih.setText(thisMovie.getName());
holder.tablooo.setImageResource(context.getResources().getIdentifier(thisMovie.getLogo(), "drawable", context.getPackageName()));
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
private TextView tozih;
private ImageView tablooo;
public MovieViewHolder(View itemView) {
super(itemView);
tozih = (TextView) itemView.findViewById(R.id.gridview_text);
tablooo = (ImageView) itemView.findViewById(R.id.gridview_image);
}
}
}
here is the grid code
the recyclerview is in a fragment and the fragment is in another activity
RecyclerView.LayoutManager layoutManager;
layoutManager = new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(layoutManager);
thanks in advance