I am using a tablayout to build my application but the tab indicator is not working when I slide within the tabs. Can anyone help me?I have tried adding the addOnTabSelectedListener but that did not work either.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private PagerAdapter pagerAdapter;
private DrawerLayout drawerLayout;
private String[] pageTitle = {"myPlanner", "News", "Parking"};
private String studyRooms = "http://library2.csumb.edu/mrbs/mobilenow.php";
public static String MYPREFERENCE = "myPref";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
setSupportActionBar(toolbar);
//create default navigation drawer toggle
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < 3; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
//set gravity for tab bar
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//handling navigation view item event
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
assert navigationView != null;
navigationView.setNavigationItemSelectedListener(this);
viewPager = (ViewPager)findViewById(R.id.view_pager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
//setting Tab layout (number of Tabs = number of ViewPager pages)
//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) {
Fragment frag = pagerAdapter.fragments[position];
if(frag != null && frag instanceof MapsFragment){
Toast.makeText(MainActivity.this, "On page Selected", Toast.LENGTH_LONG).show();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
// viewPager.setOffscreenPageLimit(3);
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
}
class PagerAdapter extends FragmentPagerAdapter{
String tabTitles[] = new String[]{"myPlanner", "News", "Parking"};
public Fragment[] fragments = new Fragment[tabTitles.length];
Context context;
public PagerAdapter(FragmentManager fm, Context context){
super(fm);
this.context = context;
}
#Override
public int getCount(){
return tabTitles.length;
}
#Override
public Fragment getItem(int position){
switch (position){
case 0:
return new myPlanner();
case 1:
return new News();
case 2:
return new MapsFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position){
//Generate title based on item position
return tabTitles[position];
}
#Override
public Object instantiateItem(ViewGroup container, int position){
Fragment createdFragment = (Fragment)super.instantiateItem(container,position);
fragments[position] = createdFragment;
return createdFragment;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[],int[] grantResults){
if(requestCode == MapsFragment.MY_PERMISSIONS_REQUEST_LOCATION){
MapsFragment mapFragment = (MapsFragment) pagerAdapter.fragments[2];
if(mapFragment != null){
mapFragment.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
}
else{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
remove this:
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
And add:
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) {
}
});
Also u should call tabLayout.setupWithViewPager(viewPager); after u set up the viewpager
viewPager = (ViewPager)findViewById(R.id.view_pager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
Related
I have a TabLayout with 3 tabs and a BottonNavigation and I need that at the moment of pressing patients and configuration the tablayout disappears, I do not know what line of code I need?
I also use a ViewPager, everything works well the only thing I need is that the TabLayout disappears when it is in patients. In the Patient Fragment I will use a recycleView and CardView, I want to show the photo of the patient and his data
project image:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
BottomNavigationView mbottomNavigation;
private ViewPager mviewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//bottomNavigation
mbottomNavigation = (BottomNavigationView) findViewById(R.id.bottom_navigation);
mbottomNavigation.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
//aqui se especifica donde es que se quiere que inicie el bottom
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AgendaFragment()).commit();
//ViewPager
mviewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(mviewPager);
final BottomNavigationView navigation=(BottomNavigationView)findViewById(R.id.bottom_navigation);
navigation.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
mviewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position){
case 0:
navigation.setSelectedItemId(R.id.nav_agenda);
break;
case 1:
navigation.setSelectedItemId(R.id.nav_pacientes);
break;
case 2:
navigation.setSelectedItemId(R.id.nav_configuracion);
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private OnNavigationItemSelectedListener navigationItemSelectedListener = new OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_agenda:
mviewPager.setCurrentItem(0);
return true;
case R.id.nav_pacientes:
mviewPager.setCurrentItem(1);
return true;
case R.id.nav_configuracion:
mviewPager.setCurrentItem(2);
return true;
}
return false;
}
};
private void setupViewPager(ViewPager mviewPager) {
BottomNavPagerAdapter adapter=new BottomNavPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new AgendaFragment());
adapter.addFragment(new PacientesFragment());
adapter.addFragment(new ConfiguracionFragment());
mviewPager.setAdapter(adapter);
}
}
PatientsFragment.java:
public class AgendaFragment<toolbar> extends Fragment {
private TabLayout tabLayout;
private ViewPager firstViewPager;
public AgendaFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView=inflater.inflate(R.layout.fragment_agenda,container,false);
firstViewPager=(ViewPager)rootView.findViewById(R.id.viewpager_content);
tabLayout=(TabLayout)rootView.findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(firstViewPager);
setupViewPager(firstViewPager);
return rootView;
}
private void setupViewPager(ViewPager viewPager) {
TabViewPagerAdapter adapter = new TabViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new Tab1Fragment(), "Today");
adapter.addFragment(new Tab1Fragment(), "Tomorrow");
adapter.addFragment(new Tab1Fragment(), "Other Date");
viewPager.setAdapter(adapter);
}
}
You could just keep your activity layout with the BottomNavigation and the FrameLayout to show the content of each navigation item. Add the AppBar with the Toolbar and TabBar in your Agenda Fragment layout.
I have viewpager which is in fragment. I am looking to start a new activity or refresh the current activity using tabs on it
For now , I'm using this to open Fragment called "Sunday" and "Monday" But I would Like to add another tab and when user select this tab either refresh the current activity as same state when app is first opened or open new activity
Here is my code
public class MainActivity extends AppCompatActivity {
//RSS link
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new sectionB(), "SEC B");
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if (tab.getPosition() == 0) {
Intent i1 = new Intent(MainActivity.this, SagarActivity.class);
startActivity(i1);
//here you can do your refresh of start new activity
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
For Refresh
If you want to refresh whole activity you can call recreate() method of activity
in your case you are in a fragment so you need to get activity first so you can do like getActivity().recreate()
For start new activity
for open a new activity you can use startActivity()
i your case you can do Like this
Intent intent = new Intent(getActivity(),activity_you_want_to_start.class);
startActivity(intent);
Remember one more thing, always make user getActivity() not returning
null
Now in your case
you need to setup listener on your TabLayout like this then call above method
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs_dayscount);
tabLayout.setupWithViewPager(viewPager);
//setting listener on tabLAyout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if (tab.getPosition() == yourDesiredPositionNumber) {
//here you can do your refresh of start new activity
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
One Another Way is
You can also set Listener on ViewPager like this
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs_dayscount);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if(position==yourDesiredPositionNumber){
//here you can do your refresh of start new activity
}
super.onPageSelected(position);
}
});
I have a FloatingActionButton in my android navigation drawer with tablayout which displays the following message :
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
homeFragment();
SnackBarMessage("Go To Inbox.");
}
});
using snackbar
public void SnackBarMessage(String message){
Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
let's say I have 3 tabs e.g (tab 0 ,tab 1 , tab 2)
how can I make the Floating action button take me to tab 2 once I click on it
This is the fragment containing the tabs
public class HomeFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager mViewPager;
private OnFragmentInteractionListener mListener;
private SectionsPagerAdapter mSectionsPagerAdapter;
ArrayList<String> tabName;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
mViewPager = (ViewPager)view.findViewById(R.id.container);
tabName=new ArrayList<String>();
int [] tabIcons = {
R.drawable.ic_home,
R.drawable.ic_move_to_inbox,
R.drawable.ic_notifications,
R.drawable.ic_swap_horiz,
R.drawable.ic_people,
};
String[] strings = { "Main Page Goes Here", "Messages Go Here", "Notifications Go Here", "Trade Page Goes Here", "People Online Page Goes Here"};
for(int i=0;i<5;i++){
tabLayout.addTab(tabLayout.newTab().setIcon(tabIcons[i]));
tabName.add((strings[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());
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(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 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;
}
#Override
public void onResume() {
super.onResume();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
To be able to do this from another Fragment you will need to send a something in a Bundle, such as the position of the page, then do something like this:
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putInt(YOUR_PAGE, youPage);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack("Name").commit();
Then in your HomeFragment:
Bundle bundle = this.getArguments();
if (bundle != null) { viewPager.setCurrentItem(bundle.getInt(YOUR_PAGE) }
I made 2 different fragments and I want them to show in the 2 tabs. One fragment after pressing the first tab and the other fragment after pressing the second tab. After switching between the two tabs, only one fragment should be shown.
my first fragment names "fragment" and my second fragment is named "fragment2"
//Hallo ich hätte gerne tabs
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//tab listener
ActionBar.TabListener tabListener1 = new ActionBar.TabListener(){
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
// für den zweiten tab
ActionBar.TabListener tabListener2 = new ActionBar.TabListener(){
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
//Tabs erstellen
actionBar.addTab(actionBar.newTab().setText("Tab Nummer Eins").setTabListener(tabListener1));
actionBar.addTab(actionBar.newTab().setText("Tab Nummer Zwei").setTabListener(tabListener2));
When you are communicating with more then one fragments better use FragmentStatePagerAdapter, which will populate required fragment on corresponding tab selected.
First Create Toolbar,Tablayout,ViewPager in your xml file.
Then Create Fragment and Fragment2.
Include this code in your HomeActivity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.list_home));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.save));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.i("tag1","on tab");
viewPager.setCurrentItem(tab.getPosition());// passing selected tab position to adapter and getting reuqired fragment
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Create a PageAdapter like this...
public class PageAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PageAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment tab1 = new Fragment(); //When click First tab
return tab1;
case 1:
Fragment2 tab2 = new Fragment2(); //When click on second tab
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
Log.i("tag1","on getcount");
return mNumOfTabs;
}
}
Hope this will help you. Let me know if you need any further help.
Hi I want to change view with the drawer selection, it work but the first view stay under the new one...
I have a superimposition of layout...
What Should i do?
Also How can i recover the id of current layout?
public class display extends MainActivity {
private String[] drawerListViewItems;
private ListView drawerListView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
drawerListViewItems = getResources().getStringArray(R.array.items);
drawerListView = (ListView) findViewById(R.id.left_drawer);
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.drawable.ic_launcher,
R.string.open,
R.string.close
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle SaveInstanceState) {
super.onPostCreate(SaveInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem target) {
if (actionBarDrawerToggle.onOptionsItemSelected(target)) {
return true;
}
return super.onOptionsItemSelected(target);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View v, int pos, long id) {
Toast.makeText(display.this, ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
selectItem(pos);
drawerLayout.closeDrawer(drawerListView);
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
break;
case 1:
fragment = new test2();
break;
case 2:
fragment = new test3();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.drawer_layout, fragment).commit();
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
drawerLayout.closeDrawer(drawerListView);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
}
If the first view remains under the new one, maybe the xml file associated with the new fragment doesn't have a background defined and it might be transparent.
Try to define android:background in the root element of the new view.
For the fragment id question, I think it's not possible to recover the id. You could store it in a global variable, or you can use string tags in order to identify the fragments, like it's done here:
get the latest fragment in backstack