Same fragment with different contents in viewpager - android

I have one parent fragment where there is viewpager and tablayout.
Viewpager holds the fragment with different contents associated with it.
Every think works fine on swipe but whenever I tap on the different tabs of the tablayout, categoryId and categoryName of SwipableFragment is changed to adjacent tab's SwipableFragmet to the visible fragment.
Basically when I launch my FragmentAllNews (containing a ViewPager) it's shown the second fragment/page instead of the first and when I swipe to the second I see the third... In other words It's always shown the next or the previous fragment/page depending on the swipe direction (left or right).
Sorry For my bad english :(
here are my Fragments and FragmentStatePagerAdater class
###1 FragmentAllNews which holds the viewpager and tablayout
public class FragmentAllNews extends Fragment {
#Bind(R.id.tab_layout)
TabLayout tabLayout;
#Bind(R.id.all_news_viewpager)
ViewPager viewPager;
SessionManager sessionManager;
String categoryId;
String categoryName;
ArrayList<TabModel> tabs;
public static FragmentAllNews createNewInstance() {
FragmentAllNews fragmentAllNews = new FragmentAllNews();
return fragmentAllNews;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionManager = new SessionManager(getActivity());
tabs = sessionManager.getSwitchedNewsValue() == 0 ?
StaticStorage.getTabData(0) :
StaticStorage.getTabData(1);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_all_news, container, false);
ButterKnife.bind(this, fragmentView);
return fragmentView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setViewPager(tabs);
setTabLayout();
}
private void setTabLayout() {
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setViewPager(ArrayList<TabModel> tabs) {
ArrayList<NewsFragmentModel> frags = new ArrayList<>();
for (int i = 0; i < tabs.size(); i++) {
if (i == 0) {
categoryId = tabs.get(i).cat_id;
categoryName = tabs.get(i).cat_name;
frags.add(new NewsFragmentModel(FragmentBreakingAndLatestNews.createNewInstance(categoryId, categoryName), categoryName));
} else {
categoryId = tabs.get(i).cat_id;
categoryName = tabs.get(i).cat_name;
frags.add(new NewsFragmentModel(SwipableFragment.createNewInstance(categoryId, categoryName), categoryName));
}
}
NewsPagerAdapter adapter = new NewsPagerAdapter(getChildFragmentManager(),frags);
viewPager.setAdapter(adapter);
}
#Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
###2 SwipableFragment which the fragment attached to the viewpager
public class SwipableFragment extends Fragment implements NewsTitlesAdapter.RecyclerPositionListener {
#Bind(R.id.recycler_view)
RecyclerView recyclerView;
#Bind(R.id.progess)
ProgressBar progressBar;
#Bind(R.id.cat_id)
TextView categoryTextView;
ArrayList<NewsObj> newsObjs;
NewsTitlesAdapter newsTitlesAdapter;
SessionManager sessionManager;
private static String categoryId;
private static String categoryName;
public static SwipableFragment createNewInstance(String category_id, String category_name) {
SwipableFragment swipableFragment = new SwipableFragment();
Bundle box = new Bundle();
box.putString(StaticStorage.NEWS_CATEGORY_ID, category_id);
box.putString(StaticStorage.NEWS_CATEGORY, category_name);
swipableFragment.setArguments(box);
return swipableFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionManager = new SessionManager(getActivity());
categoryId = getArguments().getString(StaticStorage.NEWS_CATEGORY_ID);
categoryName = getArguments().getString(StaticStorage.NEWS_CATEGORY);
newsObjs = (sessionManager.getSwitchedNewsValue() == 0) ?
NewsData.getNewsRepublica(getActivity()) :
NewsData.getNewsNagarik(getActivity(),categoryName);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_swipable, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i("category", categoryId + " " + categoryName);
categoryTextView.setText(categoryId+" "+categoryName);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
newsTitlesAdapter = new NewsTitlesAdapter(newsObjs);
newsTitlesAdapter.setOnRecyclerPositionListener(this);
recyclerView.setAdapter(newsTitlesAdapter);
recyclerView.addOnScrollListener(new EndlessScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int current_page) {
Log.i("categoryId", categoryId+" "+categoryName);
categoryTextView.setText(categoryId+" "+categoryName);
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
ArrayList<NewsObj> moreNews = sessionManager.getSwitchedNewsValue() == 0 ?
NewsData.getNewsRepublica(getContext()) :
NewsData.getNewsNagarik(getContext(),categoryName);
int curSize = newsTitlesAdapter.getItemCount();
newsObjs.addAll(moreNews);
newsTitlesAdapter.notifyItemRangeInserted(curSize, newsObjs.size() - 1);
progressBar.setVisibility(View.GONE);
}
}, 5000);
}
});
}
#Override
public void onChildItemPositionListen(int position, View view) {
if (view.getId() == R.id.news_share_text_view) {
} else if (view.getId() == R.id.news_show_detail_text_view) {
} else {
Intent newsDetailIntent = new Intent(getActivity(), NewsDetailActivity.class);
NewsObj newsObj = newsObjs.get(position);
newsObj.setNewsCategory(categoryName);
newsDetailIntent.putExtra(NewsDetailActivity.NEWS_TITLE_EXTRA_STRING, newsObj);
startActivity(newsDetailIntent);
}
}
}
###3 NewsPagerAdapter is the subclass extended from FragmentStatePagerAdapter
public class NewsPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<NewsFragmentModel> frags;
public NewsPagerAdapter(FragmentManager fm) {
super(fm);
}
public NewsPagerAdapter(FragmentManager fm,ArrayList<NewsFragmentModel> frags){
super(fm);
this.frags = frags;
}
#Override
public Fragment getItem(int position) {
return frags.get(position).getFrag();
}
#Override
public int getCount() {
return frags.size();
}
#Override
public CharSequence getPageTitle(int position) {
return frags.get(position).getTitle();
}
}
###4 NewsFragmentModel
public class NewsFragmentModel {
private Fragment frag;
private String title;
public NewsFragmentModel(Fragment frag, String title) {
this.frag = frag;
this.title = title;
}
public Fragment getFrag() {
return frag;
}
public void setFrag(Fragment frag) {
this.frag = frag;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Am I doing any mistakes ? please help me.If you need more info please let me know. My final hope is Stackoverflow

Related

TabLayout always shows the last fragment

I am trying to fill Tablayout from 2 different fragments depending on the value (0 or 1) of the argument Radios.newInstance(int type)
The first fragment contains all radio stations and the second contains the favorite stations
But it shows me always the fragment containing the favorite stations
public class HomeFragment extends Fragment {
public static final String TAG = "HomeFragment";
private SectionsPagerAdapter mSectionsPagerAdapter;
private ProgressBar mProgressView;
private ViewGroup mContainer;
private BaseActivity activity;
public HomeFragment() {
}
public static HomeFragment newInstance() {
return new HomeFragment();
}
public void showProgress(final boolean show) {
mContainer.setVisibility(show ? View.GONE : View.VISIBLE);
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
activity = (BaseActivity) getActivity();
activity.findViewById(R.id.tabs).setVisibility(View.VISIBLE);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
activity.getSupportActionBar().show();
mProgressView = (ProgressBar) activity.findViewById(R.id.progress);
mContainer = container;
showProgress(true);
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.container);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(RadiosFragment.newInstance(0));
fragments.add(RadiosFragment.newInstance(1));
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(), fragments);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) activity.findViewById(R.id.tabs);
tabLayout.setVisibility(View.VISIBLE);
tabLayout.setTabMode(TabLayout.GRAVITY_CENTER);
tabLayout.setupWithViewPager(mViewPager);
showProgress(false);
return view;
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
mFragments = fragments;
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "RADIOS";
case 1:
return "FAVORITES";
default:
return null;
}
}
}
}
This is the fragment that i want to show, if type == 0 it shows the all radio stations, and if type == 1 it shows the favorite stations
public class RadiosFragment extends Fragment {
private static String TYPE = "NONE";
private FirebaseRecyclerAdapter<FireBaseManager.Radio, ViewHolder> mAdapter = null;
private FirebaseRecyclerAdapter<FireBaseManager.Favorites, ViewHolder> mAdapter_fav = null;
private RecyclerView recyclerView;
public ArrayList<FireBaseManager.Favorites> listOrder;
public RadiosFragment() { }
public static RadiosFragment newInstance(int type) {
if (type == 1 )
TYPE = "favorite";
else
TYPE = "radios";
RadiosFragment fragment = new RadiosFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
final Context context = view.getContext();
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
recyclerView = (RecyclerView) view.findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
Query query = FireBaseManager.Radio.Ref.orderByChild(FireBaseManager.Radio.Table.Name.text);
ProgressDialog progressDialog = new ProgressDialog(getContext());
if (TYPE == "favorite"){
....
#Override
protected void populateViewHolder(ViewHolder viewHolder, FireBaseManager.Favorites model, int position) {
...
viewHolder.Initialize(Data);
...
}
};
recyclerView.setAdapter(mAdapter_fav);
}
});
}
else if(TYPE == "radios") {
....
#Override
protected void populateViewHolder(ViewHolder viewHolder, FireBaseManager.Radio model, int position) {
...
viewHolder.Initialize(Data);
...
});
}
};
recyclerView.setAdapter(mAdapter);
});
}
return view;
}
}
I think the problem has to do with onCreateView / onCreate but i am no sure, can you help me please.
This might help you.
mViewPager.setCurrentItem(0);
Add this line after you setup tabLayout with viewpager
thank you very much for your answers, i have found a solution for my problem.
the solution is to add Listener on the Tablayout and intercept the events.
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0)
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.flContent, RadiosFragment.newInstance(0), FavoriteActivity.TAG).addToBackStack(null).commit();
if (tab.getPosition() == 1)
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.flContent, RadiosFragment.newInstance(1), FavoriteActivity.TAG).addToBackStack(null).commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});

push data from Fragment to Fragment

I am new to Android. Please excuse me if it's a silly question:
If i click on button of a Fragment - it has to trigger a test and show the result in other Fragment. So to make things simple, have written a code on button click as follows. It's not working. Please suggest.
My actual intent is to register a log.add BroadcastReceiver, so that anywhere any log error or debug is called, that message has to appear in the TestStatusFragment.
public class TriggerTestFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_trigger, container, false);
Button stopScheduler = (Button) view.findViewById(R.id.testButton);
stopScheduler.setOnClickListener((View sview) -> {
View teststatusView = inflater.inflate(R.layout.fragment_teststatus, container, false);
TextView textView = (TextView) teststatusView.findViewById(R.id.text_view);
textView.setText("test result....");
});
return view;
}
}
MainActivity.java
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TriggerTestFragment(), "TRIGGERTEST");
adapter.addFragment(new TestStatusFragment(), "TEST STATUS");
viewPager.setAdapter(adapter);
}
Second Fragment:
public class TestStatusFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getContext();
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_teststatus, container, false);
return view;
}
}
Use interface to communicate between them.
Fragment One
public class FragOne extends Fragment {
EditText etxtName, etxtDesc;
Button btnSubmit;
String name, desc;
private OnFragmentInteractionListener mListener;
public FragOne() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frag_one, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
etxtName = (EditText) view.findViewById(R.id.etxtName);
etxtDesc = (EditText) view.findViewById(R.id.etxtDesc);
btnSubmit = (Button) view.findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = etxtName.getText().toString().trim();
desc = etxtDesc.getText().toString().trim();
if(name == null || desc == null) {
Toast.makeText(getActivity(), "Both fields required", Toast.LENGTH_SHORT).show();
} else {
mListener.onFragmentInteraction(name, desc);
etxtName.setText("");
etxtDesc.setText("");
}
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String name, String desc);
}
}
Fragment Two
public class FragTwo extends Fragment implements FragOne.OnFragmentInteractionListener{
TextView textView, textDesc;
public FragTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frag_two, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = (TextView) view.findViewById(R.id.txtName);
textDesc = (TextView) view.findViewById(R.id.txtDesc);
}
#Override
public void onFragmentInteraction(String name, String desc) {
textView.setText(name);
textDesc.setText(desc);
}
}
Init fragments
fragOne = new FragOne();
fragTwo = new FragTwo();
PagerAdapter
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
MainActivity need implement onFragmentInteraction interface
public class MainActivity extends AppCompatActivity implements FragOne.OnFragmentInteractionListener{
static FragOne fragOne;
static FragTwo fragTwo;
MyPagerAdapter myPagerAdapter;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragOne = new FragOne();
fragTwo = new FragTwo();
viewPager = (ViewPager) findViewById(R.id.viewPager);
myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(myPagerAdapter);
}
#Override
public void onFragmentInteraction(String name, String desc) {
myPagerAdapter.onFragmentInteraction(name, desc );
}
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
}
You can read full article here https://www.mytrendin.com/passing-data-between-fragments/

ViewPager not working properly, when scrolling showing wrong positions

TabLayout not working properly, when scrolling right it works correctly sometime but after scrolling left it shows same data. I'm calling Same Fragment class nine times in SectionPagerAdapter and trying to change data dynamically in Recyclerview.
ViewPagerFragment Class
public class ViewPagerFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager mViewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
// private ArrayList tabName;
private String[] tabName = {"bangladesh","international","economy" ,"opinion","sports","entertainment", "features","life-style","northamerica"};
public ViewPagerFragment() {
}
public ViewPagerFragment newInstance(String navigation) {
ViewPagerFragment fragment = new ViewPagerFragment();
Bundle args = new Bundle();
args.putString(Constants.FRAG_A, navigation);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test_fragment, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
mViewPager = (ViewPager)view.findViewById(R.id.container);
for(int i=0; i<=8; i++){
tabLayout.addTab(tabLayout.newTab().setText(tabName[i]));
}
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition()); Log.v("pagerF ^&%&^^&: ",tabName[tab.getPosition()]);
getChildFragmentManager().beginTransaction().addToBackStack(null).commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Note that we are passing childFragmentManager, not FragmentManager
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public void onResume() {
super.onResume();
if (mSectionsPagerAdapter!=null){
mSectionsPagerAdapter.notifyDataSetChanged();
}
}
SectionsPagerAdapter Class
public class SectionsPagerAdapter extends FragmentPagerAdapter {
int mNumOfTabs;
String[] tabName;
public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs, String[] tabName) {
super(fm);
this.mNumOfTabs = NumOfTabs;
this.tabName=tabName;
}
#Override
public Fragment getItem(int position) {
HomeFragment comn = new HomeFragment();
return comn.newInstance(tabName[position-1]);
}
#Override
public int getCount() {
Log.v("Count*^&*^ ", String.valueOf(mNumOfTabs));
return mNumOfTabs;
}
}
HomeFragment Class
public class HomeFragment extends Fragment {
public static String fragmentName = "";
HorizontalAdapter adapterhor; VerticalAdapter adapterver;
ProthomAlo prothomAlo;
RecyclerView recyclerViewh, recyclerViewv;
public HomeFragment newInstance(String navigation) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(Constants.FRAG_A, navigation);
fragment.setArguments(args);
fragmentName = navigation;
Log.v("home^^* :", navigation);
return fragment;
}
public HomeFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
recyclerViewh = view.findViewById(R.id.recycler_View_ho);
recyclerViewv = view.findViewById(R.id.recycler_View_ver);
prothomAlo = new ProthomAlo();
prothomAlo.getProthomAloPage(fragmentName, new ProthomAlo.ApiCallback() {
#Override
public void onSuccess(ArrayList<SingleVertical> result) {
adapterhor = new HorizontalAdapter(getActivity(), result);
adapterver = new VerticalAdapter(getActivity(), result);
recyclerViewh.setAdapter(adapterhor); recyclerViewv.setAdapter(adapterver);
recyclerViewv.setLayoutManager(new LinearLayoutManager(getActivity()));
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerViewh.setLayoutManager(layoutManager);
// Log.v("$^&^$$^&", fragmentName);
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
//adapterver.notifyDataSetChanged(); adapterhor.notifyDataSetChanged();
Log.v("home^^* :", fragmentName);
}
}

Update the row item data of recyclerview

The fragment consists of View Pager which shows the product count that
needs to be updated when the product is deleted or added .
public class SubCategoryFragment extends BaseFragment implements OnItemClickListener
{
private View rootView;
private MasterCategory subCategory;
private RecyclerView subCategoryRecyclerView;
private SubCategoryListAdapter subCategoryListAdapter;
private ArrayList<MasterCategory> superSubCategories;
private String iconImageURL;
private ArrayList<MerchantOrder> merchantorder;
/*private IRequestComplete iRequestComplete;*/
private int categoryId;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
return rootView = inflater.inflate(R.layout.fragment_category_list, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
initialiseUI();
}
initialise fragment
protected void initialiseUI()
{
categoryId = getArguments().getInt("categoryId");
iconImageURL = (String) getArguments().getSerializable("iconImageURL");
subCategory = (MasterCategory) getArguments().getSerializable("data");
subCategoryRecyclerView = (RecyclerView) rootView.findViewById(R.id.category_list_rc_view);
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
subCategoryRecyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(context);
subCategoryRecyclerView.setLayoutManager(mLayoutManager);
superSubCategories = subCategory.getCategories();
rootView.findViewById(R.id.dashboard_progressbar_newlyadded).setVisibility(View.GONE);
if (superSubCategories != null && !superSubCategories.isEmpty())
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories, iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
subCategoryListAdapter.setmOnItemClickListener(this);
updateListView();
}
else
{
rootView.findViewById(R.id.text_no_order_error).setVisibility(View.VISIBLE);
((TextView) rootView.findViewById(R.id.text_no_order_error)).setText("No Category found!");
}
}
Update the listview
private void updateListView()
{
if (subCategoryListAdapter == null)
{
subCategoryListAdapter = new SubCategoryListAdapter(superSubCategories,iconImageURL);
subCategoryRecyclerView.setAdapter(subCategoryListAdapter);
}
else
{
subCategoryListAdapter.notifyDataSetChanged();
}
subCategoryListAdapter.notifyDataSetChanged();
}
the itemclick opens up a fragment which displays the product details
#Override
public void onItemClick(View view, int position)
{
/*MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryProductsFragment superSubCategoryProductsFragment = new SuperSubCategoryProductsFragment();
superSubCategoryProductsFragment.setArguments(bundle);
manageFragment(superSubCategoryProductsFragment, SuperSubCategoryProductsFragment.class.getName(), CategoryDetailsFragment.class.getName(), bundle);*/
/*ArrayList<MasterCategory> superSubCategories = subCategoryListAdapter.getSuperSubCategory(position).getCategories();
if (null != superSubCategories){
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
SuperSubCategoryListFragment categoryDetailsFragment = new SuperSubCategoryListFragment();
categoryDetailsFragment.setArguments(bundle);
manageFragment(categoryDetailsFragment, SuperSubCategoryListFragment.class.getName(), SubCategoryFragment.class.getName(), null);
}*/
MasterCategory superSubCategories = subCategoryListAdapter.getSuperSubCategory(position);
superSubCategories.getSubCategoryCount();
superSubCategories.getProductCount();
subCategoryListAdapter.notifyDataSetChanged();
if (superSubCategories.isHasChildCategory())
{
Bundle bundle = new Bundle();
bundle.putSerializable("data", superSubCategories);
Intent intent = new Intent(context, BaseFragmentActivity.class);
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SuperSubCategoryFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
else
{
Intent intent = new Intent(context, BaseFragmentActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("categoryId", superSubCategories.getCategoryId());
bundle.putString("categoryName", superSubCategories.getName());
bundle.putBoolean("isSubCatProducts", !superSubCategories.isHasChildCategory());
bundle.putInt("ProductCount", superSubCategories.getProductCount());
intent.putExtra("toolbarTitle", superSubCategories.getName());
intent.putExtra("FragmentClassName", SubCategoryProductsFragment.class.getName());
intent.putExtra("data", bundle);
startActivity(intent);
}
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView)
{
super.onAttachedToRecyclerView(subCategoryRecyclerView);
subCategoryRecyclerView.getAdapter().notifyDataSetChanged();
}
}
This is my Adapter attached to the fragment
public class SubCategoryListAdapter extends RecyclerView.Adapter<SubCategoryListAdapter.ViewHolder> implements View.OnClickListener {
private static final String TAG = SubCategoryListAdapter.class.getSimpleName();
private ArrayList<MasterCategory> superSubCategories;
private ImageLoader imageloader;
private com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener;
private String iconImageURL;
#Override
public void onClick(View view)
{
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(view, (Integer) view.getTag());
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView name;
public TextView productCount;
public NetworkImageView image;
public ViewHolder(View itemLayoutView)
{
super(itemLayoutView);
productCount = (TextView) itemLayoutView.findViewById(R.id.product_count);
name = (TextView) itemLayoutView.findViewById(R.id.name);
image = (NetworkImageView) itemLayoutView.findViewById(R.id.image);
}
}
public SubCategoryListAdapter(ArrayList<MasterCategory> superSubCategories, String iconImageURL)
{
this.superSubCategories = superSubCategories;
imageloader = Global.getInstance().getImageLoader();
this.iconImageURL = iconImageURL;
}
#Override
public SubCategoryListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.super_category_list_row, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position)
{
holder.name.setText("" + superSubCategories.get(position).getName());
holder.image.setDefaultImageResId(R.drawable.logo_amoda);
holder.image.setImageUrl(iconImageURL, imageloader);
if(!superSubCategories.get(position).isHasChildCategory())
{
holder.productCount.setText("" + superSubCategories.get(position).getProductCount());
}
else
{
holder.productCount.setText("");
holder.productCount.setBackgroundResource(R.drawable.icn_right_arrow);
}
holder.itemView.setTag(position);
holder.itemView.setOnClickListener(this);
}
public void setmOnItemClickListener(com.amoda.androidlib.intf.OnItemClickListener mOnItemClickListener)
{
this.mOnItemClickListener = mOnItemClickListener;
}
#Override
public int getItemCount()
{
if (superSubCategories != null)
return superSubCategories.size();
else
return 0;
}
public MasterCategory getSuperSubCategory(int position)
{
return superSubCategories.get(position);
}
}
This is my View pager in my activity
private void showSubCategoryTabs()
{
setToolbarTitle(category != null ? category.getName() : "");
try
{
mPromotionalImage.setDefaultImageResId(R.drawable.nodeals_img);
mPromotionalImage.setImageUrl(category.getImageUrl(), imageLoader);
}
catch (Exception e)
{
e.printStackTrace();
}
tabContent = new ArrayList<String>();
for (MasterCategory subCategories : category.getCategories())
{
/*Check if the sub-sub category has super-sub category or not.*/
if (null != subCategories.getCategories())
tabContent.add(subCategories.getName());
}
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
#Override
public void onPageSelected(int position)
{
Fragment fragment = ((SectionsPagerAdapter) mViewPager.getAdapter()).getFragment(position);
if (fragment != null)
{
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter
{
private SectionsPagerAdapter sectionspageradapter;
private FragmentManager fragmentManager=null;
private Bundle bundle=new Bundle();
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
fragmentManager=fm;
}
#Override
public Object instantiateItem(ViewGroup container,int position)
{
Object obj=super.instantiateItem(container,position);
if(obj instanceof Fragment)
{
Fragment f=(Fragment)obj;
String tag=f.getTag();
f.onResume();
}
return obj;
}
#Override
public Fragment getItem(int position)
{
MasterCategory subCategories = category.getCategories().get(position);
if (subCategories.isHasChildCategory())
{
SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("iconImageURL", category.getIconImageUrl());
bundle.putSerializable("data", category.getCategories().get(position));
subCategoryFragment.setArguments(bundle);
return subCategoryFragment;
}
else
{
SubCategoryProductsFragment subCategoryProductsFragment = new SubCategoryProductsFragment();
Bundle bundle = new Bundle();
bundle.putInt("categoryId", subCategories.getCategoryId());
bundle.putString("categoryName", subCategories.getName());
bundle.putBoolean("isSubCatProducts", true);
subCategoryProductsFragment.setArguments(bundle);
return subCategoryProductsFragment;
}
}
#Override
public int getCount()
{
return tabContent.size();
}
#Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
return tabContent.get(position);
}
public Fragment getFragment(int position)
{
String tag = String.valueOf(mMerchantSubCategories.get(position));
return fragmentManager.findFragmentByTag(tag);
}
}
#Override
public void onResume()
{
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
super.onResume();
}
#Override
protected void onPause()
{
super.onPause();
}
#Override
public void onStop()
{
super.onStop();
//*Unregister event bus when the app goes in background*//*
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
#Override
public void onDestroy()
{
super.onDestroy();
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
public void onError(VolleyError volleyError)
{
UIHelper.stopProgressDialog(mProgressDialog);
Functions.Application.VolleyErrorCheck(this, volleyError);
}
just add this method to your viewPager adapter and your problem is solved.
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
this is override method of viewPager.
when you swipe one fragment to another it will automatically refresh page.
try this approach.. maybe its work for you..
put this code in your SubCategoryListAdepter
public void delete(int position) { //removes the row
superSubCategories.remove(position);
notifyItemRemoved(position);
}
make onClickListener to your ViewHolder:
suppose you click on your text and this row will be deleted.
#Override
public void onClick(View v) {
if(v.getId() == R.id.name){
//calls the method above to delete
delete(getAdapterPosition());
}
now you can also add data like this way.. thats working fine at runtime.. no need to refresh your page.

Calling methods between fragments

This is very simplified problem that I have regarding to Fragments and calling methods between fragments. I have put in the code place where I think calling method should be. Correct me if I'm wrong or if you have right solution for my problem. MainFragment extends Fragment because it is not activity... I have navigation drawer so that is how it suppose to be... :)
public class MainFragment extends Fragment{
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pager, container, false);
adapter = new CategoriesPagerAdapter(getChildFragmentManager(),Titles,Numboftabs);
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// ...here I need to call method "writeText()" in both fragments to update both TextViews also in both fragments (tabs)
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
Tab1Class tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
Tab2Class tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
}
Tab2Class:
public class Tab1Class extends Fragment {
TextView tv1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tv1 = (TextView) rootView.findViewById(R.id.tv1);
writeText();
}
public void writeText(){
tv1.setText("TV1 text");
}
}
Tab1Class:
public class Tab2Class extends Fragment {
TextView tv2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab2, container, false);
tv2 = (TextView) rootView.findViewById(R.id.tv2);
writeText();
}
public void writeText(){
tv2.setText("TV2 text");
}
}
.
.
.
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/////////////////////////Added////////////
adapter.callWrite();
////////////////////////////////////////
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
/////////////////////Added///////////////////
Tab1Class tab1;
Tab2Class tab2;
//////////////////////////////
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
////////////////////////////Added////////////////////
public void callWrite(){
if(tab1 != null)
tab1.writeText();
if(tab2 != null)
tab2.writeText();
}
/////////////
.
.
.
Here's an alternative:
public class BlankFragment extends Fragment {
public static final String ACTION_SOME_STUFF_HAPPENED = "stuff_happened_yo";
public static final String EXTRA_STUFF = "this_is_stuff";
public static void notifyStuffHappening(Context context, String stuff){
Intent intent = new Intent(ACTION_SOME_STUFF_HAPPENED);
intent.putExtra(EXTRA_STUFF, stuff);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
private StuffHappenedReceiver mStuffListener;
public static class StuffHappenedReceiver extends BroadcastReceiver {
final BlankFragment mFragment;
public StuffHappenedReceiver(BlankFragment fragment) {
this.mFragment = fragment;
// listen for changes to the account we're using
IntentFilter filter = new IntentFilter(ACTION_SOME_STUFF_HAPPENED);
LocalBroadcastManager.getInstance(fragment.getContext()).registerReceiver(this, filter);
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_SOME_STUFF_HAPPENED.equals(action)) {
mFragment.someStuffHappened(intent.getStringExtra(EXTRA_STUFF));
}
}
}
private void someStuffHappened(String stringExtra) {
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mStuffListener = new StuffHappenedReceiver(this);
}
#Override
public void onDetach() {
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mStuffListener);
mStuffListener = null;
super.onDetach();
}
}
This shows the basics of a fragment that will register a broadcast receiver automatically as it attaches / detaches from the activity.
If the fragment is not attached, it won't be updated.
To update this fragment, call the static method "notifyStuffHappening"

Categories

Resources