Refresh RecyclerView in TabLyout - android

I have Activity with LastTransactionsFragment, this fragment contains TabLayout with 3 tabs (AllTransactionsFragment , IncomesTransactionsFragment and OutgoesTransactionsFragment). All the tabs shows RecyclerView with list of transactions. User can delete row in each fragments. I need to implement if user delete row in 2nd fragment it also delete it immediately in 1st fragment. For now it delete row in main fragment and in database, but not in others fragments. It changes when i move to other and go back. All fragments look the same:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_all_transactions_list, container, false);
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
ArrayList<TransactionModel> lastTransactionsList = databaseHelper.getAllTransactionList();
Collections.reverse(lastTransactionsList);
RecyclerView recyclerView = view.findViewById(R.id.rv_allTransactionsList);
adapter = new LastTransactionsAdapter(getContext(), lastTransactionsList, false);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
EDIT
here is short video of the issue: https://streamable.com/398zke
EDIT 2
On Fragment with TabLayout
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position== 0){
IncomesTransactionsListFragment fragment = new IncomesTransactionsListFragment();
fragment.refreshRecyclerView();
} else if (position == 1){
AllTransactionsListFragment allTransactionsListFragment = new AllTransactionsListFragment();
allTransactionsListFragment.refreshRecyclerView();
} else if (position == 2){
AllTransactionsListFragment allTransactionsListFragment = new AllTransactionsListFragment();
allTransactionsListFragment.refreshRecyclerView();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
and the method in each fragments:
public void refreshRecyclerView(){
adapter.notifyDataSetChanged();
}
EDIT 3
main fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_last_transactions, container, false);
final ViewPager viewPager = view.findViewById(R.id.vp_allTransactions);
TabLayout tabLayout = view.findViewById(R.id.tl_allTransactions);
adapter = new TransactionsViewPagerAdapter(getChildFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.addOnTabSelectedListener(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) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 0){
IncomesTransactionsListFragment fragment = new IncomesTransactionsListFragment();
System.out.println(0);
fragment.refreshRecyclerView();
} else if (position == 1){
AllTransactionsListFragment allTransactionsListFragment = new AllTransactionsListFragment();
System.out.println(1);
allTransactionsListFragment.refreshRecyclerView();
} else if (position == 2){
AllTransactionsListFragment allTransactionsListFragment = new AllTransactionsListFragment();
System.out.println(2);
allTransactionsListFragment.refreshRecyclerView();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return view;
}
}
tab fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_all_transactions_list, container, false);
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
ArrayList<TransactionModel> lastTransactionsList = databaseHelper.getAllTransactionList();
Collections.reverse(lastTransactionsList);
RecyclerView recyclerView = view.findViewById(R.id.rv_allTransactionsList);
adapter = new LastTransactionsAdapter(getContext(), lastTransactionsList, false);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
public void refreshRecyclerView(){
adapter.notifyDataSetChanged();
}
}

You need to add the addOnPageChangeListener() to update any fragments data from activity. for ex.
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetpxl) {
}
#Override
public void onPageSelected(int position) {
/*get your fragments instance and write one method in that fragment to refresh the list. call this method from here*/
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Use this link for reference: https://www.legendblogs.com/blog/how-to-use-tablayout-in-viewpager-with-recyclerview/121810

Related

Display Alert in Fragment inside a ViewPager not working

I'm using an awesome library : Alerter. I have 3 fragments inside a ViewPager. When I display a fragment, I want to display an Alert with this library. However, the alert is not showing up the first time. When I click on a button to display a new one, the first one shuws and juste after the second one. Just like the alert was delayed until a new one is requested.
Here is the ocde I use for the Main Fragment :
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) view.findViewById(R.id.tabs);
ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
final MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
FragmentLifecycle fragmentToShow = (FragmentLifecycle) adapter.getItem(position);
fragmentToShow.onResumeFragment();
}
});
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Cube", "Osselet", "Watch"};
private MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
// Return Map Fragment
if (position == 0) {
return new RecordCubeFragment();
}
//Return Toilet List Fragment
else if (position == 1) {
return new RecordOsseletFragment();
}
else if (position == 2) {
return new RecordWatchFragment();
}
else {
return new RecordCubeFragment();
}
}
And there is the code of a child fragment in the ViewPager :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.d(TAG, "call oncreateview");
View v = inflater.inflate(R.layout.fragment_record_cube, container, false);
lectureButton = (ImageButton) v.findViewById(R.id.lectureButton);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Log.d(TAG, "call onview created");
super.onViewCreated(view, savedInstanceState);
lectureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Alerter.create(getActivity())
.setTitle("Warning !")
.setText("second alert.")
.setIcon(R.drawable.alert_icon)
.setBackgroundColorInt(Color.RED)
.setDuration(2000)
.show();
}
});
Alerter.create(getActivity())
.setTitle("Warning !")
.setText("first alert.")
.setIcon(R.drawable.alert_icon)
.setBackgroundColorInt(Color.RED)
.setDuration(2000)
.show();
}
Thx for the help, I know that lifeCycle of fragments is different in ViewPager, this is why I implemented an OnPageChangeListener but I cannot get rid of this problem.

Android - TabLayout, Fragments - which function is run after swipe?

I have implemented in my application tab swiping with ViewPager, Fragments etc. Everything is working fine. But I would like to know which function is run after swiping to next tab? Because I need to refresh some data when user will swipe to next screen.
I have this functions in my activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.activity_main_sensors_p, container, false);
return rootview;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
update_data();
display_items();
}
YourFragment extends Fragment {
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (this.isVisible()) {
....
} else {
....
}
}
}
You can try set OnPageChangeListener listener to your ViewPager and do action accrding to the current position in pager adapter:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// do action accroding to the viewPager position
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Using viewpager with radiogroup to switch between fragments

I have a viewpager with swipeable fragments and also a radiogroup that shows which view is selected. When I start the application, the first radiobutton is not selected, it is only selected when I swipe another view and get back. I am a beginner, so please share your knowledge. Here's my code:
Viewpager Adapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public static int int_items = 3;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new WelcomeOneFragment();
case 1:
return new WelcomeTwoFragment();
case 2:
return new WelcomeThreeFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
Fragment with the radiogroup:
public class TabFragment extends BaseFragment implements ViewPager.OnPageChangeListener, View.OnClickListener {
public static ViewPager mViewPager;
private Button mButtonMassage;
private RadioGroup mRadioGroup;
public static TabFragment newInstance() {
return new TabFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
initUi(rootView);
return rootView;
}
#Override
public void initUi(View rootView) {
mRadioGroup = (RadioGroup) rootView.findViewById(R.id.radio_group);
mViewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
mButtonMassage = (Button) rootView.findViewById(R.id.buttonMassage);
initListeners();
}
#Override
public void initListeners() {
mButtonMassage.setOnClickListener(this);
mViewPager.addOnPageChangeListener(this);
initData();
}
#Override
public void initData() {
mViewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager()));
mViewPager.setCurrentItem(0);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonMassage:
Intent i = new Intent(getActivity(), MassageActivity.class);
startActivity(i);
break;
default:
break;
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mRadioGroup.check(mRadioGroup.getChildAt(position).getId());
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
just call this
mRadioGroup.check(mRadioGroup.getChildAt(0).getId());
after
mViewPager.setCurrentItem(0);
as listner will not callup in starting and you have to set it for manually after setting adapter to viewpager
hope it will work for you!! :)
This is a pretty common issue with ViewPager. onPageSelected is not called upon start, so I would just call:
mRadioGroup.check(mRadioGroup.getChildAt(0).getId());
In your initUi() method.

ViewPager, same Fragment with RecyclerView for multiple tabs

I am working on a app, which having a category list.
If we click on category then I have to show different subcategories in tabs, each tab having a list of products.
Everything is working fine tabs and fragment are loaded with correct data, only recyclerview onClick gives incorrect item(items from adjacent fragment's recyclerview). Mostly happens on viewpager swipe.
code in Activity:
PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount(), response);
// response is a list of subcategories and products
viewPager.setOffscreenPageLimit(1);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
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) {
}
});
code in PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
SubCategoryResponse response;
public PagerAdapter(FragmentManager fm, int NumOfTabs, SubCategoryResponse response) {
super(fm);
this.mNumOfTabs = NumOfTabs;
this.response = response;
}
#Override
public Fragment getItem(int position) {
L.m(position +" => "+response.getList().get(position).getProducts().get(0).getName());
TabFragment fragmentDummy = TabFragment.getInstance(position, response.getList().get(position).getProducts());
return fragmentDummy;
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
code in TabFragment:
public class TabFragment extends Fragment implements ProductAdapter.mClickListener {
#Bind(R.id.list_container_fragment)
LinearLayout listContainerFragment;
#Bind(R.id.list_products)
RecyclerView productListView;
private ProductAdapter productsAdapter;
private Dialog myDialog;
private LinearLayoutManager linearLayoutManager;
private ArrayList<Products> responseProducts = null;
public TabFragment() {
// Required empty public constructor
}
public static TabFragment getInstance(int position, ArrayList<Products> response) {
TabFragment fragmentDummy = new TabFragment();
Bundle args = new Bundle();
args.putParcelableArrayList("PRODUCTS", response);
args.putInt("position", position);
fragmentDummy.setArguments(args);
return fragmentDummy;
}
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.responseProducts = args.getParcelableArrayList("PRODUCTS");
}
#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
View view = inflater.inflate(R.layout.fragment_tab, container, false);
ButterKnife.bind(this, view);
linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
productListView.setLayoutManager(linearLayoutManager);
productListView.setItemAnimator(new DefaultItemAnimator());
populateList();
return view;
}
public void populateList() {
L.m("populate list");
if (responseProducts.size() > 0) {
L.m("Inside populate list => " + responseProducts.get(0).getName());
productsAdapter = new ProductAdapter(responseProducts);
productsAdapter.setListner(getActivity(), this);
productListView.setAdapter(productsAdapter);
productListView.setHasFixedSize(true);
} else {
showError("No Products to Show");
}
}
public void showError(String msg) {
SnackbarManager.show(
Snackbar.with(getActivity()) // context
.text(msg) // text to be displayed
.textColor(Color.WHITE) // change the text color
// .textTypeface(myTypeface) // change the text font
.color(getResources().getColor(R.color.colorPrimary)) // change the background color
.duration(Snackbar.SnackbarDuration.LENGTH_LONG)
, getActivity());
}
#Override
public void mClickDetails(View view, int pos) {
startActivity(new Intent(getActivity(), ProductDetailsActivity.class)
.putExtra("PRODUCT", responseProducts.get(pos).getName()));
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
//populateList();
}
}
I don't know whats going wrong here.
Please help, Thank You.
Well fixed the problem,
Removed static field from RecyclerView Adapter.
Now working fine.

ViewPager update Fragment

viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
getActionBar().setSelectedNavigationItem(position);
if(position == 1)
{
new FragmentFavorites().update(getApplicationContext());
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
update from FragmentFavorites
public void update(Context context) {
savedFacts = com.invizorys.sexpro.util.Util.readFactsList(context);
if (savedFacts.size() > 0)
mTextView.setText(savedFacts.get(currentFactIndex));
else
mTextView.setText("you still have not saved any fact");
}
when I turn on FragmentFavorites application crashes(mTextView nullpointer), despite the fact that I find it in onCreateView()
mTextView = (TextView) rootView.findViewById(R.id.textview_fact);
Update
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_favorites, container, false);
...
mTextView = (TextView) rootView.findViewById(R.id.textview_fact);
...
return rootView;
}
When you new a FragmentFavorites instance, the onCreateView() is not called yet. You should find the FragmentFavorites instance from ViewPager instead of creating one.

Categories

Resources