I want to call Fragment from Adapter Class but not able to do so..
So please some method to call the fragment. I have got a method of first calling activity and then switching the fragment is there any other method
Here is the code:
public class FanAdapter extends RecyclerView.Adapter<FanAdapter.MyViewHolder>
{
private Context mContext;
private List<Fan> FanList;
public class MyViewHolder extends RecyclerView.ViewHolder
{
public TextView testTitle;
public CardView mCardView;
public MyViewHolder(View view)
{
super(view);
mCardView = (CardView) view.findViewById(R.id.card_view);
testTitle = (TextView) view.findViewById(R.id.fan_name);
}
}
public FanAdapter(Context mContext, List<Fan> FanList)
{
this.mContext = mContext;
this.FanList = FanList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fanslist, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Fan album = FanList.get(position);
holder.testTitle.setText(album.getName());
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Slecteditem= String.valueOf(position);
Bitmap bmp = BitmapFactory.decodeResource(Resources.getSystem(), position);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Fragment fragment = new ProfileDisplay();
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
Bundle args = new Bundle();
args.putString("itemname", Slecteditem);
args.putByteArray("picture", byteArray);
fragment.setArguments(args);
fragmentTransaction.replace(R.id.fl_toplayout, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Toast.makeText(mContext,"Profile"+album.getName(),Toast.LENGTH_LONG).show();
}
});
// loading album cover using Glide library
}
#Override
public int getItemCount()
{
return FanList.size();
}
}
The editor is not able to resolve getActivity() method in
FragmentManager fm = getActivity().getFragmentManager();
Pass the mContext to getFragmentManager();. Cast the mContext to Activity.
Something like this.
FragmentManager fm = (Activity)mContext.getFragmentManager();
The better way to do so would be using a interface to notify the class which calls the adapter.
Something like this:
public interface NotifyChange {
void onItemClicked();
}
Then in onItemClicked() do the operation, you want to achieve.
Considering your question, if you a calling the FanAdapter class in a fragment, create a FragmentManager inside FanClass List like this
private FragmentManager fragment;
public FragmentManager getFragment() {
return fragment;
}
public void setFragment(FragmentManager fragment) {
this.fragment = fragment;
}
and also add it to the Fan constructor
public Fan(FragmentManager fm){
this.fragment=fm;
}
In your OnClickListener body
FragmentTransaction ft=fan.get(position).getFragment().beginTransaction();
ft.replace(R.id.nav_host_fragment,fd);
ft.commit();
In Your List you should add getFragmentManager();
fan.add(new fan(your,own,variables,getFragmentManager()));
Use this code for replacing fragment from adapter class;
Fragment fragment = new YourFragmentName();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
Bundle args = new Bundle();
args.putString("itemname", Slecteditem);
args.putByteArray("picture", byteArray);
fragment.setArguments(args);
Related
I can't wrap my head around how to update the data being displayed by a RecyclerView when the RecyclerView is in a Fragment. I have an ArrayList of Strings which is where the members I'm trying to display are stored. If I predefined the list in either the Fragment script OR the main-activity in which the Fragment is hosted, it'll get displayed on the RecyclerView just fine. But then I try to update the list at run time and I am totally lost. How do I update the list at run time??
In my application, I'm trying to scan for BT devices in the area and display the results of the scan onto this RecyclerView. I know the scan portion is working fine, I can get an ArrayList of Strings containing the MAC addresses of all scanned devices in the area. I tried passing the updated data to the Fragment script via a setter, but it crashes when it reaches that point in the code.
//This is what I use to define each device
public class Device{
private String deviceName;
public Device(String name){
this.deviceName = name;
}
}
//----------------------------------------
//This is the adapter for the RecyclerView
public class deviceAdapter extends RecyclerView.Adapter<deviceAdapter.ViewHolder>{
private List<Device> deviceList;
public deviceAdapter(List<Device> deviceList){
this.deviceList= deviceList;
}
//>>>>Data is set here<<<<
public void setData(List<Device> deviceList) {
this.deviceList = deviceList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView deviceTextView;
public Button connectButton;
public ViewHolder(View itemView){
super(itemView);
deviceTextView = (TextView) itemView.findViewById(R.id.deviceDescription);
connectButton = (Button)itemView.findViewById(R.id.connectButton);
}
}
#Override
public deviceAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View deviceItemLayout = inflater.inflate(R.layout.deviceitem, parent, false);
ViewHolder viewHolder = new ViewHolder(deviceItemLayout);
return viewHolder;
}
#Override
public void onBindViewHolder(deviceAdapter.ViewHolder viewHolder, int position) {
viewHolder.deviceTextView.setText(deviceList.get(position).getName());
}
#Override
public int getItemCount() {
return data.length;
}
//---------------------------------------
//Fragment that contains the RecyclerView
public class HomeFragment extends Fragment {
private List<Device> deviceList = new ArrayList<>();
//>>>> Adapter is created here<<<<
deviceAdapter adapter = new deviceAdapter(deviceList);
RecyclerView rvDevices;
public HomeFragment(List<Device> deviceList){
this.deviceList = deviceList;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
rvDevices = (RecyclerView) rootView.findViewById(R.id.rvDevices);
rvDevices.setLayoutManager(new LinearLayoutManager(getContext()));
rvDevices.addItemDecoration(new DividerItemDecoration(rvDevices.getContext(), DividerItemDecoration.VERTICAL));
//>>>>Adapter is set here<<<<
rvDevices.setAdapter(adapter);
rvDevices.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
public void updateFragmentData(List<Device> deviceL){
this.deviceList = deviceL;
if(adapter != null){
adapter.setData(deviceList);
adapter.notifyDataSetChanged();
}
}
}
//-------------------------------------------------
//my main-activity (relevant parts)
public class Interface extends AppCompatActivity {
//Located at onCreate()
homeFragment = new HomeFragment(scannedDevicesMAC);
fragment = homeFragment
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabSelected(TabLayout.Tab tab){
switch(tab.getPosition()){
case 0:
fragment = homeFragment;
break;
case 1:
fragment = new JavaFragment();
break;
case 2:
fragment = new AndroidFragment();
break;
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
//...
});
final BroadcastReceiver mReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent incoming)
{
String iAction = incoming.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(iAction)){
BluetoothDevice tmpScannedDevices = incoming.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String tmpMACAddress = tmpScannedDevices.getAddress();
int tmpRSSI = incoming.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String tmpDeviceName = tmpScannedDevices.getName();
scannedDevicesBTOs.add(tmpScannedDevices);
scannedDevicesMAC.add(new Device(tmpMACAddress));
//This is the list I'm trying to display
scannedDevicesList.add("Name: " + tmpDeviceName + " || Address: " + tmpMACAddress + " || RSSI:" + tmpRSSI);
if(fragment != null){
homeFragment.updateFragmentData(scannedDevicesMAC);
}
}
}
};
public void scanDevices(){
if(mBTAdapter.isEnabled()){
scannedDevicesList.clear();
scannedDevicesMAC.clear();
scannedDevicesBTOs.clear();
if(mBTAdapter.isDiscovering()){
mBTAdapter.cancelDiscovery();
}
Log.d("scanDevices|scanDevices", "Scanning for BT devices");
mBTAdapter.startDiscovery();
}
}
As mentioned, I expect the RecyclerView that's held in a Fragment to display the contents of an ArrayList of Strings which is being updated from main-activity. I'm at the end of my line, been trying to figure this out for a few days!
In your Fragment create the function below
public void updateFragmentData(Device[] data){
this.data = data;
if(adapter != null){
adapter.setData(data);
adapter.notifyDataSetChanged();
}
}
and then from your Activity call
if(fragment != null){
fragment.updateFragmentData(data);
}
The above is a quick solution. An even better one would be to use interfaces to update the fragment.
Updated
In your activity you should declare these three
HomeFragment homeFragment;
JavaFragment javaFragment;
AndroidFragment androidFragment;
and then in the onCreate() initialise them
homeFragment = new HomeFragment(data);
javaFragment = new JavaFragment();
androidFragment = new AndroidFragment();
and then you need to update only the homeFragment so the code will look like this
if(homeFragment != null){
homeFragment.updateFragmentData(data);
}
public void setData(List<Device> deviceList) {
this.deviceList.clear;
this.deviceList.addAll(deviceList);
notifyDatasetChanged();
}
So you do not need to notifyDatasetChanged in your fragment now.
in my activity i have simple FrameLayout widget and i'm trying to attach simple fragment to that by replace and using some fragment into nested fragment but i get Fragment already added error when i try to add some fragment in nested fragment, for example this is my activity:
public class MainActivity extends AppCompatActivity {
private CarouselFragment carouselFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
if (savedInstanceState == null) {
initScreen();
} else {
carouselFragment = (CarouselFragment) getSupportFragmentManager().getFragments().get(0);
}
...
}
private void initScreen() {
carouselFragment = new CarouselFragment();
final FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, carouselFragment)
.commit();
}
}
and nested fragment is CarouselFragment class :
in this fragment i'm trying to set some other fragment to adapter to use them
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_carousel, container, false);
ButterKnife.bind(this, view);
context = getContext();
viewPager = (ViewPagerCustomDuration) view.findViewById(R.id.vp_pages);
adapter = new CarouselViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new FragmentA());
adapter.addFragment(new FragmentB());
viewPager.setAdapter(adapter);
viewPager.setPageMargin(50);
viewPager.setOffscreenPageLimit(3);
viewPager.setScrollDurationFactor(4);
viewPager.setOffscreenPageLimit(1);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
and then this is my adapter:
public class CarouselViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
public CarouselViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
#Override
public CharSequence getPageTitle(int position) {
return null;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
mFragmentList.add(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
mFragmentList.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return mFragmentList.get(position);
}
}
Problem is this lines of codes:
adapter.addFragment(new FragmentA());
adapter.addFragment(new FragmentB());
You can only replace fragments that you added dynamically via a FragmentTransaction.
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Try using tutorial :-http://sapandiwakar.in/replacing-fragments/
Have a look at this:- Replacing a fragment with another fragment inside activity group
Hope this will help you.
I am developing an app for displaying images and text. When clicking on the item it goes to another fragment. The listing showing is correct but when I click on the item it does not go to fragment. I am using recycler adapter to listing the items. The code is shown below.
public class MyRecyclerAdapter extends RecyclerView.Adapter < MyRecyclerAdapter.MyViewHolder > {
String categoryId;
private List < NewsFeeds > feedsList;
private Context context;
private LayoutInflater inflater;
public MyRecyclerAdapter(Context context, List < NewsFeeds > feedsList) {
this.context = context;
this.feedsList = feedsList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = inflater.inflate(R.layout.singleitem_recyclerview_categories, parent, false);
return new MyViewHolder(rootView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NewsFeeds feeds = feedsList.get(position);
//Pass the values of feeds object to Views
holder.title.setText(feeds.getName());
//holder.categoryId.setText(feeds.getCategory_id());
categoryId = feeds.getCategory_id();
Log.d("LOGTAG", "id : " + categoryId);
holder.imageview.setImageUrl(feeds.getImgURL(), NetworkController.getInstance(context).getImageLoader());
Log.d("LOGTAG", "feeds.getFeedName():" + feeds.getName());
}
#Override
public int getItemCount() {
return feedsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private NetworkImageView imageview;
private CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title_view);
//categoryId = (TextView) itemView.findViewById(R.id.content_view);
// Volley's NetworkImageView which will load Image from URL
imageview = (NetworkImageView) itemView.findViewById(R.id.thumbnail);
cardView = (CardView) itemView.findViewById(R.id.card_view);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
Log.d("LOGTAG", categoryId);
Log.d("LOGTAG", "clicked");
//newInstance(categoryId);
}
});
}
}
}
I want to send value to SubCategoryFragment and start SubCategoryFragment.
my SubCategoryFragment code
public class SubCategoryFragment extends Fragment {
public SubCategoryFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sub_category, container, false);
//Bundle bundle = this.getArguments();
Bundle args = getArguments();
//String categoryId = args.getString("index");
String categoryId = getArguments().getString("category_id");
//String categoryId = getArguments().getString("category_id");
TextView textView = (TextView) rootView.findViewById(R.id.label);
textView.setText(categoryId);
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
Please help me
From Adapter you send data with intent as:
Fragment fragment = new tasks();
FragmentManager fragmentManager = context.getSupportFragmentManager(); // this is basically context of the class
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle bundle=new Bundle();
bundle.putString("name", "From Adapter"); //key and value
//set Fragmentclass Arguments
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
String strtext=getArguments().getString("name"); //fetching value by key
return inflater.inflate(R.layout.fragment, container, false);
}
In your onClickListener();
Fragment fragment = new tasks();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Change R.id.content_frame with your fragment
You have made one mistake in your onClick method.
When you want to go one fragment to other fragment, you have to transaction the fragment using FragmentTransaction.class
Check out below code.
Edit :
SecondFragment fragment = new SecondFragment();
FragmentManager fragmentManager = currentfragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.content_frame, fragment);
fragmentTransaction.hide(currentfragment) fragmentTransaction.addToBackStack(currentfragment.getclass().getsimplename());
fragmentTransaction.commit();
Edit :
Just put below code in your RecyclerViewAdapter method onBindViewHolder.
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
FragmentManager fragmentManager = currentfragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.content_frame, fragobj);
fragmentTransaction.hide(currentfragment);
fragmentTransaction.addToBackStack(currentfragment.getclass().getsimplename());
fragmentTransaction.commit();
//newInstance(categoryId);
}
});
EDIT :
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder> {
String categoryId;
private List<NewsFeeds> feedsList;
private Context context;
private LayoutInflater inflater;
private Fragment currentFragment;
public MyRecyclerAdapter(Context context, List<NewsFeeds> feedsList, final Fragment currentFragment) {
this.context = context;
this.feedsList = feedsList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.currentFragment = currentFragment;
}
#Override
public MyRecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = inflater.inflate(R.layout.singleitem_recyclerview_categories, parent, false);
return new MyViewHolder(rootView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NewsFeeds feeds = feedsList.get(position);
//Pass the values of feeds object to Views
holder.title.setText(feeds.getName());
//holder.categoryId.setText(feeds.getCategory_id());
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
FragmentManager fragmentManager = currentfragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.content_frame, fragobj);
fragmentTransaction.hide(currentfragment);
fragmentTransaction.addToBackStack(currentfragment.getclass().getsimplename());
fragmentTransaction.commit();
//newInstance(categoryId);
}
});
}
#Override
public int getItemCount() {
return feedsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title_view);
}
}
}
Replace your onclick listener with this.
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
Log.d("LOGTAG", categoryId);
Log.d("LOGTAG", "clicked");
//put this in your code
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.SubCategoryFragment, fragobj);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
//newInstance(categoryId);
}
});
I have ViewPager as the first item inside a RecyclerView.I want to set FragmentStatePagerAdapter to the viewpager inside the onBindViewHolder() method.
But i can't call getsupportfragmentmanager().Please help!!.
Here's my code:
public class CustomListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<RowItem> rowItemList;
private final int VIEW_TYPE_CUSTOM = 0;
private final int VIEW_TYPE_NORMAL = 1;
NewPagerAdapter mCustomPagerAdapter;
public CustomListAdapter(Context context, List<RowItem> rowItemList) {
this.context = context;
this.rowItemList = rowItemList;
}
#Override
public int getItemViewType(int position) {
if (position == 0)
return VIEW_TYPE_CUSTOM;
else
return VIEW_TYPE_NORMAL;
}
#Override
public int getItemCount() {
return rowItemList.size()+1;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case VIEW_TYPE_CUSTOM:
recViewHolder1 viewHolderSecond = (recViewHolder1) holder;
mCustomPagerAdapter = new NewPagerAdapter(getSupportFragmentManager());
viewHolderSecond.vPager.setAdapter(mCustomPagerAdapter);
break;
case VIEW_TYPE_NORMAL:
recViewHolder2 viewHolderFirst = (recViewHolder2) holder;
RowItem rowItem = rowItemList.get(position-1);
viewHolderFirst.vName.setText(rowItem.getName());
viewHolderFirst.vImage.setImageResource(rowItem.getImageId());
break;
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case VIEW_TYPE_CUSTOM:
View itemView = LayoutInflater.
from(parent.getContext()).
inflate(R.layout.pagerlayout, parent, false);
return new recViewHolder1(itemView);
case VIEW_TYPE_NORMAL:
View itemView1 = LayoutInflater.
from(parent.getContext()).
inflate(R.layout.rowlayout, parent, false);
return new recViewHolder2(itemView1);
}
return null;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
public static class recViewHolder1 extends RecyclerView.ViewHolder {
protected static ViewPager vPager;
public recViewHolder1(View v) {
super(v);
vPager = (ViewPager) v.findViewById(R.id.vPager);
}
}
public class recViewHolder2 extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView vName;
protected ImageView vImage;
public recViewHolder2(View v) {
super(v);
v.setOnClickListener(this);
vName = (TextView) v.findViewById(R.id.vName);
vImage = (ImageView) v.findViewById(R.id.vImage);
} } }
i solved it by casting mContext
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
Its Best solution is to pass the reference of your Context to the Adapter from Your Activity (or) Fragment.
public UsersAdapter(ArrayList<User> items , Context context) {
usersList = items;
this.context = context;
}
Then upcast context to AppCompatActivity like this and get the getSupportFragmentManager
((AppCompatActivity) context).getSupportFragmentManager()
Share to improve.
Here you can set transition ;)
public void pushFragment(Fragment newFragment, Context context){
FragmentTransaction transaction = ((FragmentActivity)context).getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, newFragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.commit();
}
FragmentManager fragmentManager = ((FragmentActivity) view.getContext()).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Try this ..it worked for me.
I worked as follows:
#Override
public void onBindViewHolder(DataAdapter.ViewHolder holder, final int position) {
holder.txtTitle.setText(list.get(position).getTitle());
holder.txtMessage.setText(list.get(position).getMessage());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = list.get(position).getTitle();
if(title.equals("FRECUENTES")){
RequestFrequentFragment fragment = new RequestFrequentFragment(); // you fragment
FragmentManager fragmentManager = ((FragmentActivity) v.getContext()).getSupportFragmentManager(); // instantiate your view context
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, fragment);// your container and your fragment
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
});
}
First you have to pass context to adapter constructor.
Then you have to use that context reference to get getSupportFragmentManager.
mCustomPagerAdapter = new NewPagerAdapter(context.getSupportFragmentManager());
viewHolderSecond.vPager.setAdapter(mCustomPagerAdapter);
Another solution...
Declare context
private Toast mssgeToast;
private Context ctxContext;
public MyViewListener(myView pView){
this.mView = pView;
this.ctxContext = pView.getContext();
}
Next...
public void pushFragment(Context context){
FragmentManager fm = ((FragmentActivity)context).getSupportFragmentManager();
PopupClickFragment pcf = new PopupClickFragment();
pcf.show(fm, "");
// FragmentTransaction transaction = ((FragmentActivity)context).getSupportFragmentManager().beginTransaction();
}
and declare into onClickListener.
Example:
#Override
public void onCellClicked (#NonNull RecyclerView.ViewHolder p_jCellView,int p_nXPosition,
int p_nYPosition){
//TODO: AQUI SE DEBE LEVANTAR EL POPUP INSTANCIANDO .SHOW();
pushFragment(ctxContext);
}
For whome using kotlin you can use this solution
val dialog = IntervAddFragment()
val ft = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
dialog.show(ft, ContentValues.TAG)
And it will work perfectly inchAllah.
For those having this error:
Inconvertible types; cannot cast 'android.content.Context' to YourFragment
I implemented this solution
Update your adapter constructor to accept the Fragment as a parameter.
Something like :
customAdapter = new CustomAdapter(myContext, android.R.layout.simple_list_item_1
, getList, YourFragment.this);
and update the constructor of the Adapter :
public CustomAdapter(Context context, int id, YourFragmentfragment) {
this.fragment = fragment;
}
then you call methods using the fragment variable.
fragment.doSomething();
The answer is by Shivam Verma.
just pass Avtivity
`public CustomListAdapter(AppCompatActivity context, List<RowItem> rowItemList) {
this.context = context;
this.rowItemList = rowItemList;
}`
and you can do everything that you can do in activities but in your adapter class
I have implemented this way, in adapter method
override fun onBindViewHolder(holder: TestViewHolder, position: Int) {
val appCompatActivity = holder.itemView.context as AppCompatActivity
timePickerDialog.show(appCompatActivity.supportFragmentManager, "dialog")
}
This solution works for me, getting context from holder, no need to send context to adapter also sending context in constructor to adapter as far as I know is bad approach.
((FragmentActivity)view.getContext()).getSupportFragmentManager().beginTransaction().replace(R.id.btm_ly, new SettingFragment()).commit();
Two fragments,
first fragment sends arraylist of product name and price to second fragment,
Second fragment gets all values properly
Question
I want to display data on TextView. How can it possible?
Below is my code
First Fragment
alists=new ArrayList<String>();
System.out.println("ARRAYLIST><><><><><"+alists);
GenericUtility.setStringToSharedPrefsForKey("selected_prodname", user_name, getActivity());
GenericUtility.setStringToSharedPrefsForKey("selected_prodprc", dollars+prod_price, getActivity());
btn_add_to_cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cartincrement();
productnams = GenericUtility.getStringFromSharedPrefsForKey("selected_prodname", getActivity());
System.out.println("Seleced user name=-=-=-=-=-=-==-=" + productnams);
productprc = GenericUtility.getStringFromSharedPrefsForKey("selected_prodprc", getActivity());
System.out.println("Seleced prodprice=-=-=-=-=-=-==-=" + productprc);
alists.add(productnams);
alists.add(productprc);
}
});
relcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Add_to_cart tf = new Add_to_cart();
Bundle bundle = new Bundle();
bundle.putStringArrayList("prodnam", alists);
// bundle.putString("prodprce", productprc);
tf.setArguments(bundle);
android.support.v4.app.FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
}
Second Fragment
public class Add_to_cart extends Fragment {
private Button continue_shopping;
private Button checkout;
ListView list;
private TextView _decrease,mBTIncrement,_value;
private CustomListAdapter adapter;
private ArrayList<String> alst;
private String bname;
public Add_to_cart(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.list_view_addtocart, container, false);
alst=new ArrayList<String>();
Bundle bundle = this.getArguments();
alst = bundle.getStringArrayList("prodnam");
System.out.println("NAM--"+alst);
/* for(int i=0;i<alst.size();i++)
{
bname=alst.get(i);
}*/
continue_shopping=(Button)rootView.findViewById(R.id.btn_continueshoppping);
checkout=(Button)rootView.findViewById(R.id.btn_chckout);
adapter = new CustomListAdapter(getActivity(),alst);
list=(ListView)rootView.findViewById(R.id.list_addtocart);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});
continue_shopping.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HomeFragment tf = new HomeFragment();
android.support.v4.app.FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Checkout tf = new Checkout();
android.support.v4.app.FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, tf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
});
return rootView;
}
public class CustomListAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> listData;
//private AQuery aQuery;
String dollars="\u0024";
public CustomListAdapter(Context context,ArrayList<String> listData) {
this.context = context;
this.listData=listData;
// aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_addtocart, null);
holder.txtproname = (TextView) convertView.findViewById(R.id.proname_addtocart);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.proprice_addtocart);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position));
holder.txtprofilecast.setText(dollars+listData.get(position));
//holder.txtprofilecast.setText(dollars+listData.get(position));
// aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtprofilecast;
}
Your problem is that your list of items is actually twice as long as it should be. If you have 4 items in your list you will have 8 entries in your array (each item has 2 entries, a name and a price).
Instead of adding the name and price to a single array, you should create 2 parallel arrays. The first containing the list of names and the second containing the list of prices. Pass both arrays to the second fragment.