I am a new application developer trying to transfer data from activity to tabLayout (TabItem ).
Firstly I make a data pass or intent from (recyclerview) to activity that contains tabLayout (TabItem ) by this code :
public static final String EXTRA_FROM = "FROMPL";
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this,
com.example.myapplication.Fragmant.StatusFragment.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_FROM, clickedItem.getCreator());
startActivity(detailIntent);
}
And I Receive data on the next Activity that contains tabLayout (TabItem ) with the following code:
Intent i = getIntent();
final String FROMPL = i.getStringExtra("FROMPL");
text.setText(FROMPL);
To here everything is fine , And the data can be used on Main page .but the problem that I have now
In this activity after I Receive data how I can send it to one of tabLayout or one TabItem ?Picture for clarification
I need to transfer data to it to display different data separately in each one.
All my code :
public class MainActivityFargmain extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
PageAdapter pageAdapter;
TabItem tabChats;
TabItem tabStatus;
TabItem tabCalls;
EditText text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_m);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.app_name));
setSupportActionBar(toolbar);
tabLayout = findViewById(R.id.tablayout);
tabChats = findViewById(R.id.tabChats);
tabStatus = findViewById(R.id.tabStatus);
tabCalls = findViewById(R.id.tabCalls);
viewPager = findViewById(R.id.viewPager);
text = (EditText) findViewById(R.id.text);
Intent i = getIntent();
final String FROMPL = i.getStringExtra("FROMPL");
text.setText(FROMPL);
pageAdapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pageAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 1) {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorAccent));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorAccent));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorAccent));
}
} else if (tab.getPosition() == 2) {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
android.R.color.darker_gray));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
android.R.color.darker_gray));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivityFargmain.this,
android.R.color.darker_gray));
}
} else {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorPrimary));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorPrimary));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorPrimaryDark));
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
}
public class ChatFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_chat, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_chats, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_chat) {
Toast.makeText(getActivity(), "Clicked on " + item.getTitle(), Toast.LENGTH_SHORT)
.show();
}
return true;
}
}
public class PageAdapter extends FragmentPagerAdapter {
private int numOfTabs;
PageAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChatFragment();
case 1:
return new StatusFragment();
case 2:
return new CallFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
Please help me
In your Activity create 2 functions:
setData()
getData()
In your MainActivity() add the following:
public String data;
public void setData(String passedData){
this.data = passedData
}
OnClick Listener function:
#Override
public void onItemClick(int position) {
setData("my String");
}
declare getData() that returns data.
public void getData(){
return data;
}
in your fragment
MainActivityFargmain activity = (MainActivityFargmain) getActivity();
String dataReceived = activity.getData();
Related
I have a problem pass or intent data from (activity) to (Fragment) containing 3 (TabLayout ).
How can I transfer data to a specific (TabLayout) of the third that I own.
by RecyclerView onItemClick.
This is code of RecyclerView onItemClick.I was send it From first activity to secand activity like this As follows..
Pass data first activity
public static final String EXTRA_FROM = "FROMPL";
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this,
com.example.myapplication.Fragmant.StatusFragment.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_FROM, clickedItem.getCreator());
startActivity(detailIntent);
}
secand activity get data
Intent i = getIntent();
final String FROMPL = i.getStringExtra("FROMPL");
textfrom.setText(FROMPL);
But now like that not work.I don’t know how I can pass it to a specific (TabLayout)to work as Fragment in (MainActivityFargmain).
I want each (TabLayout) in (MainActivityFargmain) has specific data.
So Anyone have a solution for that؟
all my code
public class MainActivityFargmain extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
PageAdapter pageAdapter;
TabItem tabChats;
TabItem tabStatus;
TabItem tabCalls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_m);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.app_name));
setSupportActionBar(toolbar);
tabLayout = findViewById(R.id.tablayout);
tabChats = findViewById(R.id.tabChats);
tabStatus = findViewById(R.id.tabStatus);
tabCalls = findViewById(R.id.tabCalls);
viewPager = findViewById(R.id.viewPager);
pageAdapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pageAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 1) {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorAccent));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorAccent));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorAccent));
}
} else if (tab.getPosition() == 2) {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
android.R.color.darker_gray));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
android.R.color.darker_gray));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivityFargmain.this,
android.R.color.darker_gray));
}
} else {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorPrimary));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorPrimary));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorPrimaryDark));
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
}
public class PageAdapter extends FragmentPagerAdapter {
private int numOfTabs;
PageAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChatFragment();
case 1:
return new StatusFragment();
case 2:
return new CallFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
public class StatusFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_status, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_status, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_status) {
Toast.makeText(getActivity(), "Clicked on " + item.getTitle(), Toast.LENGTH_SHORT)
.show();
}
return true;
}
}
public class ChatFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_chat, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_chats, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_chat) {
Toast.makeText(getActivity(), "Clicked on " + item.getTitle(), Toast.LENGTH_SHORT)
.show();
}
return true;
}
}
You are passing the data to fragment from first activity and you are fetching data from second activity.
But in a proper scenario you should pass the data to second activity. Then after you can fetch it.
public static final String EXTRA_FROM = "FROMPL";
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this,
MainActivityFargmain.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_FROM, clickedItem.getCreator());
startActivity(detailIntent);
}
Fetch the data in MainActivityFragmain using below code.
Intent i = getIntent();
final String FROMPL = i.getStringExtra("FROMPL");
pageAdapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount(),FROMPL);
viewPager.setAdapter(pageAdapter);
Update your Pager adapter class like below.
public class PageAdapter extends FragmentPagerAdapter {
private int numOfTabs;
private String FROMPL;
PageAdapter(FragmentManager fm, int numOfTabs, String FROMPL) {
super(fm);
this.numOfTabs = numOfTabs;
this.FROMPL = FROMPL;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChatFragment();
case 1:
StatusFragment statusFragment = new StatusFragment();
Bundle bundle=new Bundle();
bundle.putString("FROMPL", FROMPL);
statusFragment.setArguments(bundle);
return statusFragment;
case 2:
return new CallFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
I have an application in which I create TabItems dynamically and I add them to the TabLayout. I'll show you the code below. then I also have a mechanism that when a tabitem is created, the user can close it with a click of a button. NOW: the problem happens here. when the user deletes that tabitem and program automatically directs the user to another tab. I can no longer click on the other tabs that I created at the start of the application. I Can click on them, but the program closes with the error
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 4, found: 3 Pager
and all of this happens when I delete a tabitem with a code written for a click. below is my MainActivity.java code :
public class MainActivity extends AppCompatActivity implements ContactsFragment.CallBacks, UserDetailFragment.DetailCallBacks {
android.support.v7.widget.Toolbar toolbar;
public static List<Fragment> fragments = new ArrayList<>();
public static List<String> fragmentsTitle = new ArrayList<>();
ViewPager viewPager;
TabLayout tabLayout;
int tabposition_number;
public List<Fragment> getFragments() {
return fragments;
}
public List<String> getFragmentsTitle() {
return fragmentsTitle;
}
public void addToFragments(Fragment fragment) {
fragments.add(fragment);
}
public void addToFragmentsTitle(String title) {
fragmentsTitle.add(title);
}
public Fragment getFragmentsWithPosition(int position) {
return fragments.get(position);
}
public String getFragmentsTitleWithPosition(int position) {
return fragmentsTitle.get(position);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = new MenuInflater(this);
menuInflater.inflate(R.menu.top_main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.remove_tab) {
remove_tab_details(3);
}
return super.onOptionsItemSelected(item);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page_drawer);
this.tabLayout = findViewById(R.id.tab_layout);
this.viewPager = findViewById(R.id.view_pager);
tabLayout.setupWithViewPager(viewPager);
SetUpViewPager(viewPager);
this.toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = findViewById(R.id.navigation_view);
navigationView.setItemIconTintList(null);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabSelected(TabLayout.Tab tab) {
if(tab.getPosition() > 2) {
tabposition_number = tab.getPosition();
}
// viewPager.setCurrentItem(tab.getPosition());
if(tab.getPosition() == 1) {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.tab_contacts));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.main_contacts));
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivity.this,R.color.status_contacts));
}
} else if(tab.getPosition() == 2) {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.tab_register));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.main_register));
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivity.this,R.color.status_register));
}
} else {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.tab_signin));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.main_signin));
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivity.this,R.color.status_signin));
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
public void SetUpViewPager(ViewPager viewPager) {
MyViewPagerAdapter Adapter = new MyViewPagerAdapter((getSupportFragmentManager()));
Adapter.AddFragmentPage(new SignInFragment(),"ورود");
Adapter.AddFragmentPage(new ContactsFragment(),"ارتباطات");
Adapter.AddFragmentPage(new RegisterFragment(),"ثبت نام");
Adapter.notifyDataSetChanged();
viewPager.setAdapter(Adapter);
}
#Override
public void create_user_detail_tab(UserObject userObject) {
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
UserDetailFragment userDetailFragment = new UserDetailFragment();
Bundle bundle = new Bundle();
bundle.putString("name",userObject.getName());
bundle.putString("family",userObject.getFamily());
bundle.putString("email",userObject.getEmail());
userDetailFragment.setArguments(bundle);
Adapter.AddFragmentPage(userDetailFragment,userObject.getName());
viewPager.setAdapter(Adapter);
TabLayout.Tab tab = tabLayout.getTabAt(1);
tab.select();
}
#Override
public void delete_previous_tab(int tabposition_number) {
remove_tab_details(tabposition_number);
MyViewPagerAdapter myViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
myViewPagerAdapter.notifyDataSetChanged();
}
#Override
public void changeTabItem(boolean mustdelete) {
ContactsFragment contactsFragment = new ContactsFragment();
if(tabposition_number > 2 && mustdelete) {
contactsFragment.setTextView(tabposition_number,mustdelete);
TabLayout.Tab tab = tabLayout.getTabAt(1);
tab.select();
}
}
public class MyViewPagerAdapter extends FragmentPagerAdapter {
public MyViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public void removeTabPage(int position) {
fragments.remove(position);
fragmentsTitle.remove(position);
MyViewPagerAdapter myViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
myViewPagerAdapter.notifyDataSetChanged();
myViewPagerAdapter.notifyDataSetChanged();
}
public void AddFragmentPage(Fragment frag,String title) {
MainActivity.this.addToFragments(frag);
MainActivity.this.addToFragmentsTitle(title);
MyViewPagerAdapter myViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
myViewPagerAdapter.notifyDataSetChanged();
}
public Fragment getItem(int position) {
return MainActivity.this.getFragmentsWithPosition(position);
}
public CharSequence getPageTitle(int position) {
return MainActivity.this.getFragmentsTitleWithPosition(position);
}
public int getCount() {
return fragments.size();
}
}
public void remove_tab_details(int tab_to_delete) {
// TabLayout.Tab tab = tabLayout.getTabAt(2);
// tab.select();
tabLayout.removeTabAt(tab_to_delete);
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
Adapter.removeTabPage(tab_to_delete);
Adapter.notifyDataSetChanged();
}
}
and the code for UserDetailFragment ( which creates when the user click on one of the items in a listview fragment .
public class UserDetailFragment extends Fragment {
View view;
DetailCallBacks detailCallBacks;
public UserDetailFragment() {}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.user_detail_fragment,null);
return view;
}
#Override
public void onResume() {
super.onResume();
final Bundle bundle = getArguments();
String name = (String) bundle.get("name");
String family = (String)bundle.get("family");
String email = (String)bundle.get("email");
TextView nameFamilytv = view.findViewById(R.id.user_detail_name_and_family);
String nameAndfamily = name + " " + family;
nameFamilytv.setText(nameAndfamily);
TextView emailtv = view.findViewById(R.id.user_detail_email);
emailtv.setText(email);
Button closebtn = view.findViewById(R.id.detail_close_button);
closebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
detailCallBacks.changeTabItem(true);
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
detailCallBacks = (DetailCallBacks)context;
}
public interface DetailCallBacks {
public void changeTabItem(boolean mustdelete);
}
and last but not least : the code for that list item that creates dynamic tabs when user clicks on its items :
public class ContactsFragment extends ListFragment {
CallBacks callBacks;
View view;
public static int came_fromTabItem;
public static boolean do_delete;
public ContactsFragment() { }
ArrayList<UserObject> userObjects;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
userObjects = intent.getParcelableArrayListExtra(Intent_Service.SERVICE_PAYLOAD);
ArrayAdapter<UserObject> userObjectArrayAdapter = new UserArrayAdapter(context,0,userObjects);
setListAdapter(userObjectArrayAdapter);
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(getActivity(), Intent_Service.class);
getActivity().startService(intent);
LocalBroadcastManager.getInstance(getActivity().getApplicationContext()).
registerReceiver(broadcastReceiver,new IntentFilter(Intent_Service.SERVICE_MESSAGE));
}
public void setTextView(int position,Boolean mustDelete) {
came_fromTabItem = position;
do_delete = mustDelete;
}
#Override
public void onResume() {
super.onResume();
if(came_fromTabItem > 2 && do_delete) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
callBacks.delete_previous_tab(came_fromTabItem);
do_delete = false;
Toast.makeText(getActivity().getApplicationContext(),String.valueOf(came_fromTabItem),Toast.LENGTH_LONG).show();
}
}, 2000);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.view = inflater.inflate(R.layout.fragment_contacts,null);
return this.view;
}
public void onListItemClick(ListView l, View v, int position, long id) {
UserObject userObject = userObjects.get(position);
callBacks.create_user_detail_tab(userObject);
}
public interface CallBacks {
public void create_user_detail_tab(UserObject userObject);
public void delete_previous_tab(int positions);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.callBacks = (CallBacks)context;
}
}
So... can anyone help me please? the problem is simple, why the error The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 4, found: 3 appears when a tabitem is removed, how can I solve it?
the problem occur because you delete a tab item and your pager still has 4 in item count , you have to make pager item count dynamic , and call notifyDataSetChanged() after you remove an item
here is an example
public class MyPagerAdapter extends FragmentPagerAdapter {
int nbrItem;
public ProfilPagerAdapter(FragmentManager fm,String token,Int nbrItem) {
super(fm);
this.nbrItem= nbrItem;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0 :
new SignInFragment();
case 1 :
new ContactsFragment()
case 2 :
new RegisterFragment()
}
return null;
}
#Override
public int getCount() {
return nbrItem;
}
public void setNbrItem(int nbrItem) {
this.nbrItem= nbrItem;
}
now when you remove an item you will pass to new number of item to your adapater
getAdapter().setNbrItem(2);
getAdapter().notifyDataSetChanged();
I solved my Problem, But with a hack, you see the error was because: TabItems are counting and indexing from 0, but as my pages are dynamically creating, I set the
getCount() method of my FragmentPagerAdapter to return the ArrayList<Fragment> fragments size , with fragments.size() , on the other hand, the size of an ArrayList doesn't count 0. so for 3 elements, instead of 0 1 2, or number 2, it returns to number 3.
so back to business, I was compelled to add null to my ArrayList and one null to my ArrayList titles, so this way when I removed my last TabItem, program doesn't crash anymore, and to be more convenient, when a user closes all Tabs , everytime user opens ( adds ) a new tab, I call fragments.removeAll(Collections.singleton(null)); to clear every null element i have inserted, for the TabTitles Too .
anyway cheers you guys, I'm sure this would be a good tutorial for those who want to create such applications because I've included all of my codes. please give a thumbs up. thanks.
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) {
}
});
I have a SwitchTabActivty with 4 items. In my case, I use the second item to get some data from the web through a recyclerview. The problem is that when I press the fourth item (it contains a button that's starting an activity) and I go back to my second tab , my recycler view is multiplied with the same data again.
Switchtabactivity :
public class SwitchTabActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private boolean pressToExit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.weather_tab);
tabLayout.getTabAt(1).setIcon(R.drawable.events);
tabLayout.getTabAt(2).setIcon(R.drawable.details_tab);
tabLayout.getTabAt(3).setIcon(R.drawable.settings_tab);
setColorTab(tabLayout);
}
private void setColorTab(TabLayout tab) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
tab.setTabTextColors(getResources().getColorStateList(R.color.tab_colors, null));
} else {
tab.setTabTextColors(getResources().getColorStateList(R.color.tab_colors));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
if (!pressToExit) {
Toast.makeText(this, "Press back again to exit.", Toast.LENGTH_SHORT).show();
pressToExit = true;
} else {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public void onResume() {
super.onResume();
pressToExit = false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_switch_tab, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return WeatherFragment.newInstance(position);
case 1:
return EventFragment.newInstance(position);
case 2:
return OwnEventFragment.newInstance(position);
case 3:
return SettingsFragment.newInstance(position);
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Weather";
case 1:
return "Events";
case 2:
return "My Events";
case 3:
return "Settings";
}
return null;
}
}
EventFragment :
public class EventFragment extends Fragment implements EventResponse {
private String latitude, longitude;
private static final String ARG_SECTION_NUMBER = "section_number";
private RecyclerView eventList;
private EventAdapter adapter;
private TextView ifNullEvents;
private final ArrayList<EventData> eventsData = new ArrayList<>();
private UserDataBase db;
private List<String> latLonList;
private ProgressBar progressBar;
public EventFragment() {
}
public static EventFragment newInstance(int sectionNumber) {
EventFragment fragment = new EventFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.event_fragment, container, false);
initView(rootView);
db = new UserDataBase(getContext());
checkLocationChanged();
latLonList = db.getLatLon();
latitude = latLonList.get(0);
longitude = latLonList.get(1);
String EVENT_BRITE_URL_PARSE = "MY_URL";
String EVENT_BRITE_TOKEN = "MY_TOKEN";
new EventBriteApi(this, getContext()).execute(EVENT_BRITE_URL_PARSE + EVENT_BRITE_TOKEN);
setupRecyclerView();
setLocationMessage();
return rootView;
}
private void initView(View view) {
eventList = (RecyclerView) view.findViewById(R.id.event_recycler_view);
ifNullEvents = (TextView) view.findViewById(R.id.text_null_location);
progressBar = (ProgressBar) view.findViewById(R.id.progress_bar_event);
}
private void checkLocationChanged() {
if (WePrefs.isLocationChanged) {
eventsData.clear();
ifNullEvents.setText(getResources().getString(R.string.waiting_for_data));
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
WePrefs.setIsLocationChanged(false);
} else {
progressBar.setVisibility(View.GONE);
ifNullEvents.setVisibility(View.GONE);
}
if (WePrefs.isNullEventLocation) {
ifNullEvents.setText(getResources().getString(R.string.no_events_found));
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.INVISIBLE);
WePrefs.setIsNullEventLocation(false);
}
}
private void setupRecyclerView() {
eventList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
eventList.setLayoutManager(linearLayoutManager);
adapter = new EventAdapter(getActivity(), eventsData);
adapter.setHasStableIds(true);
eventList.setAdapter(adapter);
}
#Override
public void onResume() {
checkLocationChanged();
setLocationMessage();
super.onResume();
}
private void setLocationMessage() {
if (eventsData.isEmpty()) {
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
} else {
ifNullEvents.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
}
progressBar.setVisibility(View.GONE);
}
#Override
public void getArray(ArrayList<EventData> data) {
eventsData.clear();
eventsData.addAll(new ArrayList<>(new LinkedHashSet<>(data)));
}
}
Adapter :
ublic class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventHolder> {
ArrayList<EventData> data;
Context context;
public EventAdapter(Context context, ArrayList<EventData> events) {
this.context = context;
data = events;
}
#Override
public EventHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RelativeLayout layout = (RelativeLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.single_event_view, parent, false);
return new EventAdapter.EventHolder(layout);
}
#Override
public void onBindViewHolder(EventHolder holder, int position) {
holder.eventName.setText(data.get(position).getEventName());
if (data.get(position).getEventImageUrl() != null) {
Picasso.with(context).load(data.get(position).getEventImageUrl()).into(holder.eventPic);
} else {
holder.eventPic.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.no_image));
}
}
#Override
public int getItemCount() {
return data.size();
}
public class EventHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView eventName;
ImageView eventPic;
RelativeLayout layout;
public EventHolder(View itemView) {
super(itemView);
eventName = (TextView) itemView.findViewById(R.id.event_name);
eventPic = (ImageView) itemView.findViewById(R.id.event_image);
layout = (RelativeLayout) itemView.findViewById(R.id.event_layout);
layout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
//context.startActivity(new Intent(context, WebViewActivity.class));
}
}
}
Those are some of my java classes that I use for this kind of thing.
Anyway, another problem is that, when I change the location ( to receive my events) I must go to another tab and after that to come back to see my events list ( I think it needs to recreate the view ) so , because of that I called onResume, but it does not help.
I have a MainActivity which has AppBar containing toolbar and TabLayout, and also ViewPager.
MainActivity holds 4 fragments home, cash, card and account.
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private AppBarLayout appBarLayout;
Window window;
#Override
#SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
window = this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(this.getResources().getColor(R.color.color_primary_green_dark));
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setTitle("Example Wallet");
toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Toast.makeText(getBaseContext(), "Tab " + position + " Onpage Selected " + viewPager.getCurrentItem(), Toast.LENGTH_SHORT).show();
if (position == 0) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_green_dark));
}
} else if (position == 1) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
tabLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
} else if (position == 2) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_yellow));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_yellow_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_yellow_dark));
}
} else if (position == 3) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_red));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_red_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_red_dark));
}
} else {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_green_dark));
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
FloatingActionButton fab1 = (FloatingActionButton) findViewById(R.id.fab);
if (fab1 != null) {
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerIntent = new Intent(MainActivity.this, Detail.class);
startActivity(registerIntent);
}
});
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FragmentMain(), "Home");
adapter.addFrag(new FragmentCash(), "Cash");
adapter.addFrag(new FragmentCard(), "Card");
adapter.addFrag(new FragmentAccount(), "Account");
adapter.addFrag(PartThreeFragment.createInstance(20), "Tab1");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
// return null to display only the icon
return mFragmentTitleList.get(position);
}
}
}
home fragment code
public class FragmentMain extends Fragment {
private List<Movie> movieList1 = new ArrayList<>();
private List<Movie> movieList2 = new ArrayList<>();
private RecyclerView recyclerView,recyclerView1;
private MovieAdapter mAdapter1,mAdapter2;
private LinearLayout cash_layout,card_layout,account_layout;
private ViewGroup c;
public FragmentMain() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.content_main, container, false);
//final android.app.ActionBar actionBar = getActivity().getActionBar();
//c=container;
recyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
cash_layout = (LinearLayout) v.findViewById(R.id.linearLayout_cash_bal);
card_layout = (LinearLayout) v.findViewById(R.id.linearLayout_card_bal);
account_layout = (LinearLayout) v.findViewById(R.id.linearLayout_account_bal);
mAdapter1 = new MovieAdapter(movieList1);
RecyclerView.LayoutManager mLayoutManager1 = new LinearLayoutManager(v.getContext());
recyclerView.setLayoutManager(mLayoutManager1);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter1);
prepareMovieData1();
cash_layout.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressWarnings("deprecation")
public void onClick(View v) {
getContext().getActionBar().setSelectedNavigationItem(2);
/*actionBar.selectTab(actionBar.getTabAt(1));
FragmentManager fm=getFragmentManager();
fm.beginTransaction().replace(R.layout.content_cash, (Fragment)new FragmentCash()).commit();
getActivity().getActionBar().setTitle("Home");
//ActionBar actionBar = getActivity().getActionBar();*/
/*FragmentCash fragment2 = new FragmentCash();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();*/
}
});
/*mAdapter2 = new MovieAdapter(movieList2);
RecyclerView.LayoutManager mLayoutManager2 = new LinearLayoutManager(v.getContext());
recyclerView1.setLayoutManager(mLayoutManager2);
recyclerView1.setItemAnimator(new DefaultItemAnimator());
recyclerView1.setAdapter(mAdapter2);
prepareMovieData2();*/
return v;
}
private void prepareMovieData1() {
movieList1.clear();
Movie movie = new Movie("info","List is empty", "To create an item, click on (+) button", "","");
movieList1.add(movie);
mAdapter1.notifyDataSetChanged();
}
/*public void onClick1(View v) {
FragmentCash fragment2 = new FragmentCash();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content,fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}*/
/*private void prepareMovieData2() {
Movie movie = new Movie("card","Card", "New Dress", "Rs.50.00","11/09/2016");
movieList2.add(movie);
mAdapter2.notifyDataSetChanged();
}*/
}
I am trying to call cash, card and account fragment from home fragment but this code
cash_layout.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressWarnings("deprecation")
public void onClick(View v) {
FragmentCash fragment2 = new FragmentCash();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
adds other fragment with home fragment visible.
The solution I need is, in the below image when I click the cash balance it slide to the cash tab with cash fragment onscreen.
It looks like you are trying to add the cash fragment on top of the view pager, or replace it all together. Instead of replacing it in the current view, I'm assuming you would like to navigate to it within the viewPager.
To do that, replace all of your onClick code with pager.setCurrentItem(//Page number with cash fragment on it)
So, your onClick would look something like this:
cash_layout.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressWarnings("deprecation")
public void onClick(View v) {
((MainActivity) getActivity()).getViewPager().setCurrentItem(//Your desired page number as int);
}
});
Or you could solve this easily with an interface.
Just create an interface to access your viewPager's operations like so.
public interface ViewPagerInterface {
ViewPager getViewPager();
}
Have your activity implement it:
public MainActivity extends AppCompatActvity implements ViewPagerInterface {
#Override
public ViewPager getViewPager() {
return this.viewPager;
}
}
Then pass that interface to your Fragments and call the getViewPager method.
viewPagerInterface.getViewPager().setCurrentItem(<my-int>);