Handling Navigation Items with Tabs and Fragments - java

I have created a navigation drawer and added a tablayout like this
activity_main
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
app_bar_main
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
android:layout_gravity="bottom"
app:tabSelectedTextColor="#fffaf0"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
I get the result shown below:
However, I tried to add fragments to the tabs so that each navigate item opens a screen that has two tabs "First Semester" and "Second Semester" whose contents are held in the fragments xml but its not working.
MainActivity
package com.lini.bdevelopers.geomaticshandbook;
//import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ViewPager viewPager;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//SectionsPagerAdapter mSectionPagerAdapter =
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
viewPager = findViewById(R.id.viewpager);
//setupViewPager(viewPager);
tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
// Create adapter for the view pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstSemester(), "First Semester");
adapter.addFragment(new SecondSemester(), "Second Semester");
viewPager.setAdapter(adapter);
}
private void setupViewPager2(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstSemester2(), "First Semester");
adapter.addFragment(new SecondSemester2(), "Second Semester");
viewPager.setAdapter(adapter);
}
private void setupViewPager3(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstSemester3(), "First Semester");
adapter.addFragment(new SecondSemester3(), "Second Semester");
viewPager.setAdapter(adapter);
}
private void setupViewPager4(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstSemeste4r(), "First Semester");
adapter.addFragment(new SecondSemester4(), "Second Semester");
viewPager.setAdapter(adapter);
}
private void setupViewPager5(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstSemester5(), "First Semester");
adapter.addFragment(new SecondSemester5(), "Second Semester");
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.year1) {
setupViewPager(viewPager);
} else if (id == R.id.year2) {
setupViewPager2(viewPager);
} else if (id == R.id.year3) {
setupViewPager3(viewPager);
} else if (id == R.id.year4) {
setupViewPager4(viewPager);
} else if (id == R.id.year5) {
setupViewPager5(viewPager);
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
The code above binds the FirstSemester() and SecondSemester() fragments to all the navigation items. This may not be the right way to go about it, so I need suggestions and help, thanks.
Secondly
How do I change the AppBar title to the title of the Navigation item selected?

Secondly How do I change the AppBar title to the title of the
Navigation item selected?
In the onNavigationItemSelected() method in your MainActivity class.. you can do something like this:
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.year1) {
getSupportActionBar().setTitle("Year 1");
setupViewPager(viewPager);
} else if (id == R.id.year2) {
getSupportActionBar().setTitle("Year 2");
setupViewPager2(viewPager);
} else if (id == R.id.year3) {
getSupportActionBar().setTitle("Year 3");
setupViewPager3(viewPager);
} else if (id == R.id.year4) {
getSupportActionBar().setTitle("Year 4");
setupViewPager4(viewPager);
} else if (id == R.id.year5) {
getSupportActionBar().setTitle("Year 5");
setupViewPager5(viewPager);
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
As for your first question, you are displaying a viewpager (first and second semester) for any item clicked in the navigation drawer so you shouldn't be expecting a normal-looking code. Crude method though but it's not too poor in efficiency.
I hope this helps.. Merry coding!

If you want to first create YearOne fragment and add the semesters to each Year then you first need to add your YearOne, YearTwo etc fragments to the navigation drawer menu.
I created a simple app to illustrate this some days back https://github.com/mbobiosio/TabLayout
You can attach your TabLayout simply like this in YearOneFragment
mViewPager.setAdapter(new FragmentsAdapter(getChildFragmentManager(), getActivity()));
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
});

I will share what i used in my application. You can reuse the single fragment. Have a look at this
Mainactivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
{
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle(R.string.app_name); //Toolbar title at start.
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment;
if (id == R.id.year1) {
fragment = new YearFragment(); //Root Fragment then add semester fragment.
loadFragment(fragment);
Bundle data = new Bundle();
data.putString("YEAR","FIRST YEAR"); //Pass year value
fragment.setArguments(data);
toolbar.setTitle("FIRST YEAR");
}
if (id == R.id.year2) {
fragment = new YearFragment();//If your view for fragment is different then create new fragment and change here.
loadFragment(fragment);
Bundle data = new Bundle();
data.putString("YEAR","SECOND YEAR"); //Pass year value
fragment.setArguments(data);
toolbar.setTitle("SECOND YEAR");
}
.
.
.
. //Add upto required navigation items.
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.commit();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
Year Fragment
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
public class YearFragment extends Fragment {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TabLayout mTabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.frag_year,container,false);
mTabLayout = rootview.findViewById(R.id.sliding_tabs);
mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity().getSupportFragmentManager());
mViewPager = rootview.findViewById(R.id.vp_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
String year = getArguments().getString("YEAR",""); //Here you can get year value change code according to year value.
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
String[] titles = {"FIRST SEMESTER"," SECOND SEMESTER"};
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
if(position == 0) {
return FirstSemester.newInstance(year);
}
else {
return SecondSemester.newInstance(year);
}
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
}
frag_year.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_scrollFlags="scroll"
app:tabIndicatorColor="#color/colorAccent"
app:tabIndicatorHeight="3dp"
app:tabMode="fixed"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
app:tabTextColor="#color/textColor" />
<android.support.v4.view.ViewPager
android:id="#+id/vp_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/sliding_tabs" />
FirstSemester.java
public class FirstSemester extends Fragment {
private static String yearValue = "";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.frag_firstsem,container,false);
if(yearValue.equals("FIRST YEAR"))
{
//Add Code as per your need.
}
return rootview;
}
public static FirstSemester newInstance(String Year) {
FirstSemester fragment = new FirstSemester();
yearValue = Year;
return fragment;
}
frag_firstsem.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
//Add your views for Semster fragment.
</android.support.constraint.ConstraintLayout>
Hope it will helps.! And i create bundle and pass year value which is used only your framents view for all navigation items are same.So you can change values according to year otherwise if your nav item views are different you should create seperate fragments for Years & seperate for semester too..

Related

How can i setup a base drawer for all activities

I have read a lot of answers here but could not manage to do it. I want all of my activities to have a drawer. Inside the drawer i have a ListView which contains all of the activities that the drawer should open. This is the implementation of the drawer:
public abstract class DrawerActivity extends BaseActivity {
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.base_drawer_layout);
drawerLayout = findViewById(R.id.drawer_layout);
drawerList = findViewById(R.id.left_drawer);
final ArrayList<String> elements = new ArrayList<>();
elements.add("My tasks");
elements.add("Issues");
drawerList.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, elements));
drawerList.setOnItemClickListener(createOnDrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view)
{
getSupportActionBar().setTitle("TITLE");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView)
{
getSupportActionBar().setTitle("Title");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
drawerLayout.addDrawerListener(drawerToggle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (drawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
protected abstract DrawerItemClickListener createOnDrawerItemClickListener();
protected ListView drawerList()
{
return drawerList;
}
protected DrawerLayout drawerLayout()
{
return drawerLayout;
}
}
This is the drawer layout xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#274"/>
</android.support.v4.widget.DrawerLayout>
Lets say i have currently two activities, My Tasks and Issues and both of them extend DrawerActivity. If i am in the Issues activity, how can i open the My Tasks activity through that drawer?
All activities that extend DrawerActivity implements createOnDrawerItemClickListener() which inside creates a new fragment with the layout of the the activity that implements DrawerActivity, which i'm pretty sure is wrong.
Example implementation:
#Override
protected DrawerItemClickListener createOnDrawerItemClickListener()
{
return new DrawerItemClickListener(position ->
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, new TaskFragment()).commit();
drawerList().setItemChecked(position, true);
drawerLayout().closeDrawer(drawerList());
});
}
And the DrawerItemClickListener:
public class DrawerItemClickListener implements ListView.OnItemClickListener {
private FragmentStrategy fragmentStrategy;
public DrawerItemClickListener(final FragmentStrategy fragmentStrategy)
{
this.fragmentStrategy = fragmentStrategy;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
fragmentStrategy.showFragment(position);
}
public interface FragmentStrategy {
void showFragment(final int position);
}
}
How can i make this work?
In your case adding fragment will be the best solution.
create a fragment BlankFragment.java
public class BlankFragment extends Fragment {
public BlankFragment() {
// 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_blank, container, false);
}
}
and create fragment_black.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.above_inc.shyam.drawer.BlankFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
now replace your method
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new BlankFragment();
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
add below code in your content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.above_inc.shyam.drawer.MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
you can also add more fragment to other options same as camera in above code

problems with With Fragments and ViewPager

have view pager with 3section . want inside this pagers put fragment . and i use this example : http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/
Main Activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
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) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
XML:
<RelativeLayout
android:id="#+id/main_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
TabFragment1 :
public class TabFragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_1, container, false);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab 1"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>
and 2more fragment class like this .
PagerAdapter :
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment3 tab3 = new TabFragment3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
so i have error in pageradapter in line :
super(fm);
and this line : public Fragment getItem(int position) {
and another error in Main activity in line :
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
You have to import the fragments from support.v4 library, you have to replace the imports for android.support.v4 like this.
import android.app.Fragment; > import android.support.v4.app.Fragment;
import android.app.FragmentManager; >importandroid.support.v4.app.FragmentManager;
import android.app.FragmentStatePagerAdapter; > import android.support.v4.app.FragmentStatePagerAdapter;

Disable swipe in tabbed activity (Android Studio)

i want to disable the swipe function in the tabbed activity. I tried some examples i found but it didn't worked or the code was completely different.
Here is my code:
MainActivity.java:
package com.example;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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_main, 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) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
return FragmentOne.newInstance("a","b");
case 1:
return FragmentTwo.newInstance("a","b");
case 2:
return FragmentThree.newInstance("a","b");
case 3:
return FragmentFour.newInstance("a","b");
case 4:
return FragmentFive.newInstance("a","b");
default:
return FragmentThree.newInstance("a","b");
}
}
#Override
public int getCount() {
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "One";
case 1:
return "Two";
case 2:
return "Three";
case 3:
return "Four";
case 4:
return "Five";
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.MainActivity"
android:background="#1d2935">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="#dimen/fab_margin"
android:src="#mipmap/icon_plus_normal"
app:backgroundTint="#1d2935" />
</android.support.design.widget.CoordinatorLayout>
You need to create Custom ViewPager Class this way .
public class CustomViewPager extends ViewPager {
private boolean swipeable = false;
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
// Call this method in your motion events when you want to disable or enable
// It should work as desired.
public void setSwipeable(boolean swipeable) {
this.swipeable = swipeable;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
return (this.swipeable) ? super.onInterceptTouchEvent(arg0) : false;
}
Now
CustomViewPager ViewPagerObj = (CustomViewPager)findViewById(R.id.container);
ViewPagerObj.setSwipeable(false);
You should add this in your XML
<Your_packagename.CustomViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
The accepted answer does not work for me. Beginners can just use this kotlin file instead of the accepted answer java file.
class CustomViewPager: ViewPager {
private var swipeable = false
constructor(context: Context) : super(context)
constructor(context:Context, attrs: AttributeSet) : super(context, attrs)
fun setSwipeable(swipeable:Boolean) {
this.swipeable = swipeable
}
override fun onInterceptTouchEvent(arg0: MotionEvent):Boolean {
return if ((this.swipeable)) super.onInterceptTouchEvent(arg0) else false
}
override fun onTouchEvent(event:MotionEvent):Boolean {
return if (this.swipeable) super.onTouchEvent(event) else false
}
}

How to use Navigation Drawer without duplicate code?

I have created a Navigation Drawer following a tutorial, but now I have a problem. How can I use it in multiple activities without duplicating the code?
I tried extending the main activity, but I found some problems with Toolbar. There's some other way?
Thanks, this is my code.
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
class NavItem {
String mTitle;
int mIcon;
public NavItem(String title, int icon) {
mTitle = title;
mIcon = icon;
}
}
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
public int getCount() {
return mNavItems.size();
}
public Object getItem(int position) {
return mNavItems.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, parent, false);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText( mNavItems.get(position).mTitle );
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
}
}
ListView mDrawerList;
RelativeLayout mDrawerPane;
private static String TAG = MainActivity.class.getSimpleName();
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
ArrayList<NavItem> mNavItems = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavItems.add(new NavItem(getString(R.string.home), R.drawable.ic_action_home));
mNavItems.add(new NavItem(getString(R.string.company), R.drawable.ic_action_company));
mNavItems.add(new NavItem(getString(R.string.services), R.drawable.ic_action_services));
mNavItems.add(new NavItem(getString(R.string.solutions), R.drawable.ic_action_solutions));
mNavItems.add(new NavItem(getString(R.string.case_history), R.drawable.ic_action_case_history));
mNavItems.add(new NavItem(getString(R.string.contacts), R.drawable.ic_action_contacts));
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerLayout.closeDrawer(mDrawerPane);
if (position == 0) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else if (position == 1) {
Intent intent = new Intent(getApplicationContext(), CompanyActivity.class);
startActivity(intent);
}
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.d(TAG, "onDrawerClosed: " + getTitle());
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item);
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
<ImageView
android:contentDescription="#string/app_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/logo" />
</RelativeLayout>
<include layout="#layout/side_menu" />
<include layout="#layout/toolbar" />
</android.support.design.widget.CoordinatorLayout>
side_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" >
<RelativeLayout
android:id="#+id/mainContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RelativeLayout
android:layout_width="280dp"
android:layout_height="match_parent"
android:id="#+id/drawerPane"
android:layout_gravity="start">
<ListView
android:id="#+id/navList"
android:layout_width="280dp"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:background="#FFF" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
toolbar.xml:
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
Create a baseactivity with your drawer inside and then extend base activity to all activities in which you want drawer.
And instead of calling setcontentview() in oncreate inheriting activities use layout inflator
Check this post
How to Display Navigation Drawer in all activities?
Here is part of real code from my project. #Bind is from awesome Butterknife library. AbstractToolbarActivity it's a sub class of the AppCompatActivity that follows the same logic (avoiding duplicating code of initializing toolbars)
public abstract class AbstractDrawerActivity extends AbstractToolbarActivity {
#Bind(R.id.drawer_layout) DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mDrawerToggle;
protected void initDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open,
R.string.drawer_close);
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
}
#Override protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
initDrawer();
mDrawerToggle.syncState();
}
#OnClick(R.id.drawer_user_name) protected void openProfile() {
final Intent profile = new Intent(this, ProfileActivity.class);
startActivity(profile);
}
// here some onclicks etc, other methods
#Override protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
}
}
#Override public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
} else {
super.onBackPressed();
}
}
#Override protected void onPause() {
super.onPause();
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
}
}
}
And AbstractToolbarActivity.java:
public abstract class AbstractToolbarActivity extends AppCompatActivity {
#Bind(R.id.action_bar) Toolbar mToolbar;
#Override protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
initToolbar();
}
protected void initToolbar() {
setSupportActionBar(mToolbar);
}
}

Can't get swipe working for swipeable tabs

I am following http://www.android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html and I have the same code. I can't get the tabs to swipe to each other and I can't view any content in the tabs. My code is below. Thanks for the help!
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="activity.MainActivity">
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar" />
<slidingModel.SlidingTabLayout
android:layout_below="#+id/toolbar"
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"
android:background="#color/primary_color"
/>
<android.support.v4.view.ViewPager
android:layout_below="#id/tabs"
android:id="#+id/pager"
android:layout_height="0dp"
android:layout_width="match_parent"
/>
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
fab:fab_colorNormal="#color/fab_normal"
fab:fab_colorPressed="#color/fab_pressed"
fab:fab_colorRipple="#color/fab_ripple"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
MainActivity.java
package activity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.gursimran.bei.forte.R;
import adapter.ViewPagerAdapter;
import slidingModel.SlidingTabLayout;
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"Factorial", "Permutation", "Random"};
int Numboftabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.fab_pressed);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#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_main, 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);
}
}
ViewPagerAdapter.java
package adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import fragment.FactorialTab;
import fragment.PermutationTab;
import fragment.RandomTab;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
FactorialTab factorialTab = new FactorialTab();
return factorialTab;
} else if(position == 1) // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
PermutationTab permutationTab = new PermutationTab();
return permutationTab;
}
else {
RandomTab randomTab = new RandomTab();
return randomTab;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
Swipe Function control by ViewPager .Your Viewpager layout_height is 0dp in here That's why have problem .
So basically set this way
android:layout_width="match_parent"
android:layout_height="wrap_content"

Categories

Resources