I have a recyclerView populated in a Fragment and I want to Launch a new Fragment and pass data from the adapter ,I try to use Bundles but it always give a null value this my Adapter Class
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private LayoutInflater inflater;
private List<Information> mList;
private FragmentCommunication mCommunicator;
public RecyclerAdapter(Context context, List<Information> list,FragmentCommunication communication) {
inflater = LayoutInflater.from(context);
mList = list;
mCommunicator=communication;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_row, parent, false);
MyViewHolder holder = new MyViewHolder(view,mCommunicator);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Information current = mList.get(position);
holder.name.setText(current.name);
holder.job.setText(current.job);
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",current.name);
bundle.putString("JOB",current.job);
fragmentB.setArguments(bundle);
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
TextView job;
FragmentCommunication mComminication;
public MyViewHolder(View itemView, FragmentCommunication Communicator) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tv_name);
job = (TextView) itemView.findViewById(R.id.tv_gob);
mComminication=Communicator;
name.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mComminication.respond(getAdapterPosition());
}
}
and this is my new Fragment that I want to launch
public class FragmentB extends Fragment {
TextView textview;
TextView textView2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_b,container,false);
textview= (TextView) view.findViewById(R.id.tv_name);
textView2= (TextView) view.findViewById(R.id.tv_job);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle arguments = getArguments();
if (arguments!=null){
String name= arguments.get("NAME").toString();
String job= arguments.get("JOB").toString();
textview.setText(name);
textView2.setText(job);}
}
}
this is how I connect Fragment and recyclerview Adapter
with interface
public interface FragmentCommunication {
void respond(int position);
}
and this the Fragment where the recyclerview is populated
public class RecyclerViewFragment extends Fragment {
RecyclerView mRecyclerView;
RecyclerAdapter mRecyclerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.recycler_fragment,container,false);
mRecyclerView= (RecyclerView) view.findViewById(R.id.recycler);
mRecyclerAdapter=new RecyclerAdapter(getActivity(),getData(),communication);
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public static List<Information> getData() {
List<Information>data=new ArrayList<>();
String[] names={"ahmed","mohammed"};
String[] jobs={"sacsd","csscs"};
for (int i=0;i<names.length;i++){
Information current=new Information();
current.name=(names[i]);
current.job=(jobs[i]);
data.add(current);
}
return data;
}
FragmentCommunication communication=new FragmentCommunication() {
#Override
public void respond(int position) {
FragmentB fragmentB=new FragmentB();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.dumper,fragmentB).commit();
}
};
}
and my mainActivity class is just add the RecyclerViewFragment
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerViewFragment fragment=new RecyclerViewFragment();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.dumper,fragment).commit();
}
}
so what is the right way to launch fragmentB and pass the data from recyclerview Adapter to fragmentB
thank you guys for the answer,I solved the problem using an interface with String values to connect the adapter with the fragment that contains the recyclerview and the other fragment here is what I did exactly :
this is the interface
public interface FragmentCommunication {
void respond(int position,String name,String job);
}
and this is the adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private LayoutInflater inflater;
private List<Information> mList;
private FragmentCommunication mCommunicator;
public RecyclerAdapter(Context context, List<Information> list,FragmentCommunication communication) {
inflater = LayoutInflater.from(context);
mList = list;
mCommunicator=communication;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_row, parent, false);
MyViewHolder holder = new MyViewHolder(view,mCommunicator);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Information current = mList.get(position);
holder.name.setText(current.name);
holder.job.setText(current.job);
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",current.name);
bundle.putString("JOB",current.job);
fragmentB.setArguments(bundle);
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
TextView job;
FragmentCommunication mComminication;
public MyViewHolder(View itemView, FragmentCommunication Communicator) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tv_name);
job = (TextView) itemView.findViewById(R.id.tv_gob);
mComminication=Communicator;
name.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mComminication.respond(getAdapterPosition(),mList.get(getAdapterPosition()).name,mList.get(getAdapterPosition()).job);
}
}
}
the fragment that contains the recyclerview
public class RecyclerViewFragment extends Fragment {
RecyclerView mRecyclerView;
RecyclerAdapter mRecyclerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.recycler_fragment,container,false);
mRecyclerView= (RecyclerView) view.findViewById(R.id.recycler);
mRecyclerAdapter=new RecyclerAdapter(getActivity(),getData(),communication);
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public static List<Information> getData() {
List<Information>data=new ArrayList<>();
String[] names={"ahmed","mohammed"};
String[] jobs={"sacsd","csscs"};
for (int i=0;i<names.length;i++){
Information current=new Information();
current.name=(names[i]);
current.job=(jobs[i]);
data.add(current);
}
return data;
}
FragmentCommunication communication=new FragmentCommunication() {
#Override
public void respond(int position,String name,String job) {
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",name);
bundle.putString("JOB",job);
fragmentB.setArguments(bundle);
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.dumper,fragmentB).commit();
}
};
}
this is the fragmentB where I get the Strings from the Adapter
public class FragmentB extends Fragment {
TextView textview;
TextView textview2;
String name;
String job;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
name=getArguments().getString("NAME");
job=getArguments().getString("JOB");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_b,container,false);
textview= (TextView) view.findViewById(R.id.getName);
textview2= (TextView) view.findViewById(R.id.getJob);
textview.setText(name);
textview2.setText(job);
return view;
}
}
If you are working with kotlin, the solution is much simpler.
Original Answer here
pass the function val itemClick: (Int) -> Unit to your adapter.
class MyRecyclerViewAdapter(params , val itemClick: (Int) -> Unit): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
internal inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
...
itemView.setOnClickListener( {itemClick(layoutPosition)} )
}
}
In your fragment use the returned value position
val myAdapter = MyRecyclerViewAdapter(params) { position ->
// do something
}
Either creating a listener interface in the adapter or using regular old getters, if I understand your question correctly.
You need to pass the Bundle to the fragment through the setArguments(Bundle args) method. Since you have not set arguments, the bundle you try to extract in your Fragment resolves to null.
You have the right idea with using a Bundle. You just need to pass it to the Fragment by calling setArguments(). Then you retrieve the Bundle in your Fragment with getArguments().
Note that instead of mList.get(position).name, you can do current.name. Similarly for job.
Another part of the problem is that you create FragmentB on two different places. In one place you also call setArguments() but do not show the fragment. In the other you show the fragment but do not call setArguments(). If you really need to do this from multiple parts of your code you should write a method to avoid these inconsistencies.
Related
I am building an Android Application which have Tab Layout in which there are Fragments and in Fragment I am displaying some value.
I have just only added hardcoded values to test the layout, but even these are not visible in the fragment.
Here is the code for ViewPagerAdapter:
public class FavouriteViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> favouriteFragmentList = new ArrayList<>(); // this line can cause crashes
private final List<String> favouriteFragmentListTitles = new ArrayList<>();
public FavouriteViewPagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int position) {
return favouriteFragmentList.get(position);
}
#Override
public int getCount() {
return favouriteFragmentListTitles.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return favouriteFragmentListTitles.get(position);
}
public void AddFragment(Fragment fragment, String title) {
favouriteFragmentList.add(fragment); // this line can cause crashes
favouriteFragmentListTitles.add(title);
}
}
I have tried the answers available already none of them solves my problem.
I debugged the application and my RecyclerViewAdapter is not even called, very strange. I have done this many time but this never happened.
Here is my code for RecyclerViewAdapter :
public class ProductsRecyclerAdapter extends RecyclerView.Adapter<ProductsRecyclerAdapter.viewHolder> {
Context context;
private List<FavouriteProducts> favouriteProductsData;
public ProductsRecyclerAdapter(Context context, List<FavouriteProducts> favouriteProductsData) {
this.context = context;
this.favouriteProductsData = favouriteProductsData;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.single_favourite_product_item, parent, false);
viewHolder vHolder = new viewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
holder.product_name.setText(favouriteProductsData.get(position).getProduct_name());
holder.product_price.setText(favouriteProductsData.get(position).getProduct_price());
holder.product_image.setImageResource(favouriteProductsData.get(position).getProduct_image());
Toast.makeText(context,favouriteProductsData.get(position).getProduct_price() , Toast.LENGTH_SHORT).show();
/*holder.heart_button.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
showSuccessToast(context,"Liked");
}
#Override
public void unLiked(LikeButton likeButton) {
showSuccessToast(context,"Unliked");
}
});*/
}
#Override
public int getItemCount() {
return favouriteProductsData.size();
}
static class viewHolder extends RecyclerView.ViewHolder {
MaterialTextView product_name, product_price;
ImageView product_image;
LikeButton heart_button;
public viewHolder(#NonNull View itemView) {
super(itemView);
product_name = itemView.findViewById(R.id.product_name);
product_price = itemView.findViewById(R.id.product_price);
product_image = itemView.findViewById(R.id.product_image);
heart_button = itemView.findViewById(R.id.heart_button);
}
}
}
I am not getting any errors but after I check adapter is not even called. Some help will be really helpful.
Fragment Code:
public class FavouriteProductsFragment extends Fragment {
View v;
private List<FavouriteProducts> productList;
public FavouriteProductsFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
productList = new ArrayList<>();
productList.add(new FavouriteProducts("All Weather", "200/Ltr", R.drawable.all_weather));
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.products_favourite_fragment, container, false);
RecyclerView productRecyclerView = v.findViewById(R.id.favourite_products_rv);
ProductsRecyclerAdapter recyclerAdapter = new ProductsRecyclerAdapter(getContext(), productList);
productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
productRecyclerView.hasFixedSize();
productRecyclerView.setAdapter(recyclerAdapter);
return v;
}
}
productList = new ArrayList<>();
productList.add(new FavouriteProducts("All Weather", "200/Ltr",R.drawable.all_weather));
recyclerAdapter.notifyDataSetChanged()
RecyclerView productRecyclerView = v.findViewById(R.id.favourite_products_rv);
ProductsRecyclerAdapter recyclerAdapter = new ProductsRecyclerAdapter(getContext(), productList);
productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
productRecyclerView.hasFixedSize();
productRecyclerView.setAdapter(recyclerAdapter);
You need to add
RecyclerView productRecyclerView = v.findViewById(R.id.favourite_products_rv);
ProductsRecyclerAdapter recyclerAdapter = new ProductsRecyclerAdapter(getContext(), productList);
productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
productRecyclerView.hasFixedSize();
productRecyclerView.setAdapter(recyclerAdapter);
productList = new ArrayList<>();
productList.add(new FavouriteProducts("All Weather", "200/Ltr",R.drawable.all_weather));recyclerAdapter.notifyDataSetChanged()
and Remove oncreate() method
try productRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); befor setting adapter in recyclerview.
Step1: First Create one or MoreFragment For Your ViewPager and in This Fragment Add your Recyclerview Code as per Your Requirement.
Like Below Code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_whatsapp_image, container, false);
context = getActivity();
((HomeActivity) getActivity()).toolbar.setVisibility(View.VISIBLE);
setupView(root);
return root;
}
private void setupView(ViewGroup root) {
recyclerView = (RecyclerView) root.findViewById(R.id.recyclerViewImage);
progressBar=root.findViewById(R.id.simpleProgressBar);
txtinfo=root.findViewById(R.id.txtinfo);
setUPList();
}
Step2: Then Create ViewPager Adapter for Your TabLayout
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if(position == 0) return new AudioFragment();
if(position == 1) return new VideoFragment();
if(position == 2) return new ImageFragment();
throw new IllegalStateException("Unexpected position " + position);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0) return "Audio";
if(position == 1) return "Video";
if(position == 2) return "Image";
throw new IllegalStateException("Unexpected position " + position);
}
}
Step3 : Then Call Your SetupViewpager Method in Your Oncreate method of your Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=findViewById(R.id.toolbar);
viewPager=findViewById(R.id.viewpager);
tabLayout=findViewById(R.id.tabs);
//add toolbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
setTabIcons();
}
NOTE: You Can Download ViewPager Code from Below Link.Click Here to View and Download
can i use ListFragment to achieve what I said above or i need a custom recycler view inside a fragment, I tried to put a recycler view inside fragment but i didn't know how to make the onClick for recycler view work with fragment so it passes data to another fragment or another activity in case of multi-pane UI, so can i use list fragment or my only choice is recycler view, if it's then how can I do it in recycler view ?
my MainActivity which has a fragment that contains the recycler view
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.main_fragment_container);
if (fragment == null) {
fragment = new FragmentRecyclerList();
fm.beginTransaction()
.add(R.id.main_fragment_container, fragment)
.commit();
}
}
}
my fragment which contains the recycler view
public class FragmentRecyclerList extends Fragment implements MyDialog.OnInputSelected {
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
private List<String> titles;
private FloatingActionButton fab;
public FragmentRecyclerList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_recycler_list, container, false);
}
void showDialog() {
MyDialog myDialog = new MyDialog();
myDialog.setTargetFragment(FragmentRecyclerList.this, 1);
myDialog.show(getFragmentManager(), "MyDialog");
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = getView().findViewById(R.id.recyclerview);
fab = getView().findViewById(R.id.floatingActionButton);
titles = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerViewAdapter = new RecyclerViewAdapter(getActivity(), titles);
recyclerView.setAdapter(recyclerViewAdapter);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
}
});
}
}
my recycler view adapter
public class RecyclerViewAdapter extends
RecyclerView.Adapter {
private Context context;
private List<String> titles;
public RecyclerViewAdapter(Context context, List<String> titles) {
this.context = context;
this.titles = titles;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_wallpaper
, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String title = titles.get(position);
holder.tvTitle.setText(title);
}
#Override
public int getItemCount() {
return titles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvTitle;
public ViewHolder(#NonNull View itemView) {
super(itemView);
View v = itemView;
tvTitle = itemView.findViewById(R.id.row_title);
}
}
}
I'm am trying to open a new fragment by selecting the image from the card view within the recycler view. Preferable using both adapter and fragment classes. How do I do that?
This is my adapter class:
public class CorporateAdapter extends RecyclerView.Adapter {
private int[] images = {
R.drawable.sample1,
R.drawable.sample2
};
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.corporate_list_row, viewGroup, false);
final MyViewHolder vHold = new MyViewHolder(view);
return vHold;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
((MyViewHolder) viewHolder).bindView(i);
}
#Override
public int getItemCount() {
return images.length;
}
private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.showImage);
mImageView.setOnClickListener(this);
}
public void bindView(int position) {
mImageView.setImageResource(images[position]);
}
#Override
public void onClick(View v) {
}
}
This is my Fragment class:
public class CorporateFragment extends Fragment {
private final int LAYOUT_LISTCORPORATE_FRAGMENT = R.layout.corporate_membership;
private View v;
private Date date;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
public CorporateFragment() {
}
public static CorporateFragment newInstance(Date date) {
CorporateFragment fragment = new CorporateFragment();
Bundle args = new Bundle();
//args.putSerializable(ARG_DATE,date);
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(LAYOUT_LISTCORPORATE_FRAGMENT, container, false);
ButterKnife.bind(this, v);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
final CorporateAdapter listAdapter = new CorporateAdapter();
recyclerView.setAdapter(listAdapter);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
}
I've seen some ways where by we can open up the new fragment straight from the adapter, but the more correct way would be having the Onclicklistener in both the fragment class and adapter class.
Is there any way I could do that? Thank you
Here is An example for You paste as it is.
Make constructor which will have an interface as parameter in adapter and override it in Fragment.
Your Fragment Code will look like this.
public class CorporateFragment extends Fragment {
private final int LAYOUT_LISTCORPORATE_FRAGMENT = R.layout.corporate_membership;
private View v;
private Date date;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
public CorporateFragment() {
}
private int[] images = {
R.drawable.sample1,
R.drawable.sample2
};
public static CorporateFragment newInstance(Date date) {
CorporateFragment fragment = new CorporateFragment();
Bundle args = new Bundle();
//args.putSerializable(ARG_DATE,date);
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(LAYOUT_LISTCORPORATE_FRAGMENT, container, false);
ButterKnife.bind(this, v);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
final CorporateAdapter listAdapter = new CorporateAdapter(getActivity(), images, new CorporateAdapter.onItemClickListener() {
#Override
public void onItemClick(View view, int position) {
/////////////////// do your on Click Stuff here...
/////////// for ex .. go to next fragment
}
});
recyclerView.setAdapter(listAdapter);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
}
}
And Your adapter is set to go like this
public class CorporateAdapter extends RecyclerView.Adapter<CorporateAdapter.MyViewHolder> {
Context context;
private int[] images;
onItemClickListener onItemClickListener;
public CorporateAdapter(Context context, int[] images, CorporateAdapter.onItemClickListener onItemClickListener) {
this.context = context;
this.images = images;
this.onItemClickListener = onItemClickListener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.corporate_list_row, viewGroup, false);
final MyViewHolder vHold = new MyViewHolder(view);
return vHold;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
((MyViewHolder) holder).bindView(position);
holder.mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListener.onItemClick(view,position);
}
});
}
#Override
public int getItemCount() {
return images.length;
}
private class MyViewHolder extends RecyclerView.ViewHolder {
private ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.showImage);
}
public void bindView(int position) {
mImageView.setImageResource(images[position]);
}
}
public interface onItemClickListener{
void onItemClick(View view , int position);
}
}
Hope it will help. Good Luck
i have made two fragments in my app.
1st fragment (EditFrag) and 2nd fragment (ListTable). i want to transfer the value of 1st fragment(from EditText of 1st fragment) to the recyclerView of 2nd fragment.
how should i do that.....i can't find right documentation.
Thank you for your concern!
MainActivity:
public class MainActivity extends AppCompatActivity implements EditFrag.TransferValue{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListTable frag1=new ListTable();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.table_value_container,frag1,"fragment");
transaction.commit();
EditFrag frag2=new EditFrag();
FragmentManager manager1=getSupportFragmentManager();
FragmentTransaction transaction1=manager1.beginTransaction();
transaction1.add(R.id.table_container,frag2,"fragment_edit");
transaction1.commit();
}
#Override
public void sendValue(String value) {
Log.d("ashu","button is pressed");
ListTable listTable = (ListTable) getSupportFragmentManager().findFragmentById(R.id.table_value_container);
listTable.receiveValue(value);
}
}
2nd fragment(ListTable):
public class ListTable extends Fragment {
public TextView myEditText1;
private RecyclerView recyclerView;
public ListTable() {
// Required empty public constructor
}
public static ListTable newInstance(String param1, String param2) {
ListTable fragment = new ListTable();
Bundle args = new Bundle();
Log.d("ashu", "new instance is called :");
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("ashu", "oncreata called by inflating: ");
View view = inflater.inflate(R.layout.fragment_list_table, container, false);
myEditText1 = (TextView) container.findViewById(R.id.table_value);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
MyAdapter a = new MyAdapter();
recyclerView.setAdapter(a);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
public void receiveValue(String value) {
myEditText1.setText(value);
}
public class MyAdapter extends RecyclerView.Adapter<MyDataViewHolder> {
#Override
public MyDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d("ashu", "oncreateview holder of adapter ia called");
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_list_table, parent, false);
return new MyDataViewHolder(view);
}
#Override
public void onBindViewHolder(MyDataViewHolder holder, int position) {
holder.myEditText.setText("Table: " + position);
}
#Override
public int getItemCount() {
return 10;
}
}
public class MyDataViewHolder extends RecyclerView.ViewHolder {
public TextView myEditText;
public MyDataViewHolder(View itemView) {
super(itemView);
Log.d("ashu", "DAta view holder is called: ");
myEditText = (TextView) itemView.findViewById(R.id.table_value);
}
}
}
1st Fragment(EditFrag):
public class EditFrag extends Fragment {
TransferValue SendData;
EditText inputvalue;
Button click;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.edit_frag_layout, container, false);
inputvalue = (EditText) view.findViewById(R.id.edit_text);
click = (Button) view.findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String received = inputvalue.getText().toString();
SendData.sendValue(received);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SendData = (TransferValue) context;
} catch (ClassCastException e) {
Log.d("ashu", "implement the methods");
throw new ClassCastException("implemented the methods");
}
}
public interface TransferValue {
public void sendValue(String value);
}
}
create the instance of fragment2 from where want to receive the value to:
public static Fragment2 createInstance(String data) {
Fragment2 fragment = new Fragment2();
Bundle bundle = new Bundle();
bundle.putString("keyword", data);
fragment.setArguments(bundle);
return fragment;
}
and the get the data as below:
Bundle bundle = getArguments();
if (bundle != null) {
String data = bundle.getString("data");
}
You can use bundle in an order to pass data to fragment:
Example:
// Set bundle as arguments to the fragment
Bundle bundle = new Bundle();
bundle.putString(MyKey1, MyValue1);
bundle.putString(MyKey2, MyValue2);
MyFragment myFragment = new MyFragment();
myFragment.setArguments(bundle);
Inside onCreateView of fragment:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.repairer_part_details_fragment, container, false);
String value1 = getArguments().getString(MyKey1);
String value2 = getArguments().getString(MyKey2);
return view;
}
There are many ways to do that. I see your codes above, and 2 fragments loaded at the same time. I usaually use one of 2 ways below to do it.
The first solution: You can use this link using obserable pattern to communication 2 fragments.
The second solution: you can use EventBus lib for communication, it 's very simple
I'm trying to load a Fragment inside an Activity and I was able to load the items. Now, what I want to do is to click the items on the list and pass it to the DetailsView.class which is a Fragment that will receive the bundle data. But everytime I click on the item I always get an error. Below is the logcat error that I'm getting
Logcat Error
java.lang.ClassCastException: com.test.example.LoadAFragment cannot be cast to com.test.example.MainActivity at com.test.example.controller.DetailsView.onCreateView(DetailsView.java:178)
line java:178
MainActivity activity = ((MainActivity) getActivity());
LoadAFragment.class
public class LoadAFragment extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_layout);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.frame_container, myFragment);
fragmentTransaction.commit();
}
}
RecyclerView Adapter
public class MyFragmentAdapter extends RecyclerView.Adapter <RecyclerView.ViewHolder> {
private List<ListModel> list;
private Context mContext = null;
private DetailsView detailsView;
public MyFragmentAdapter(Context context, List<ListModel> list) {
mContext = context;
this.list = list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
final ListModel list = list.get(holder.getAdapterPosition());
String mID = list.getID();
final int id = Integer.valueOf(mID );
((MyViewHolder) holder).title.setText(list.getTitle());
((MyViewHolder) holder).caption.setText(list.getCaption());
((MyViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = ((Activity) mContext).getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
detailsView = new DetailsView ();
detailsView.setTitle(title);
detailsView.setArguments(bundle);
transaction.replace(R.id.frame_container, detailsView);
transaction.addToBackStack("list");
transaction.commit();
}
});
}
#Override
public int getItemCount() {
return (list != null? list.size():0);
}
private class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public TextView caption;
MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
caption = (TextView) itemView.findViewById(R.id.caption );
}
}
}
MyFragment.class
public class MyFragment extends Fragment{
List<ListModel> list;
RecyclerView mRecyclerView;
MyFragmentAdapter myFragmentAdapter;
ListDb listDb;
public MyFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
listDb = new ListDb(getActivity());
list = listDb.getList();
myFragmentAdapter = new MyFragmentAdapter (getActivity(), list);
mRecyclerView.setAdapter(myFragmentAdapter);
return rootView;
}
}
DetailsView.class
public class DetailsView extends Fragment{
private MainActivity activity;
Bundle b;
public DetailsView() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
b = savedInstanceState.getBundle("save");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
activity = ((MainActivity) getActivity());
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (b != null) {
setTitle(b.getString("title"));
id = b.getInt("id");
}
if (b != this.getArguments().getInt("id")) {
b = this.getArguments().getInt("id");
//get data from id
}
}
}
The best and cleanest solution would be to pass a listener to the adapter.
public interface MyClickListener {
void onResult(Data data);
}
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public MyAdapter(Context context, MyClickListener listener, List<ListModel> list) {
mContext = context;
this.list = list;
this.listener = listener;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
Data data = getData(position);
//bind views
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onResult(data);
}
});
}
}
Have the Fragment implement the listener and create the new adapter.
public class MyFragment extends Fragment implements MyClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyAdapter adapter = new MyAdapter(getActivity(),this,listData);
}
#Override
public void onResult(Data data) {
//do work after an item is clicked
}
}
Cast getActivity() to 'LoadAFragment' instead of 'MainActivity' in DetailsView.java. This way:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
activity = ((LoadAFragment) getActivity());
return rootView;
}
try this way to get Reference of MainActivity in your DetailViewFragment
private MainActivity parent_activity;
#Override
public void onAttach(Activity activity)
{
parent_activity = (MainActivity.class.isAssignableFrom(activity
.getClass())) ? (MainActivity) activity : null;
super.onAttach(activity);
}
#Override
public void onDetach()
{
parent_activity = null;
super.onDetach();
}
Now use the reference using:
if(parent_activity!=null)
{
parent_activity.someMethod();
}