I can't get this to work. The basic app functions as it's supposed to but the ViewPager on one of the layout files doesn't show any fragment at all. I checked the code multiple times but I can't find a bug. When I tried debugging it I noticed that it doesn't even initialize the fragments classes which it's supposed to when you select a tab.
My MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
new GetData(this).execute();
TabLayout tab_layout = (TabLayout) findViewById(R.id.tab_layout);
tab_layout.addTab(tab_layout.newTab().setText("CASUAL"));
tab_layout.addTab(tab_layout.newTab().setText("RANKED"));
tab_layout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tab_layout.getTabCount());
viewPager.setAdapter(adapter);
tab_layout.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 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.nav_stats) {
// Handle the camera action
} else if (id == R.id.nav_about) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My 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:
CasualStats tab1 = new CasualStats();
return tab1;
case 1:
RankedStats tab2 = new RankedStats();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
Layout with the ViewPager:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"><![CDATA[
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
]]>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/tab_layout">
</android.support.design.widget.TabLayout>
<view
android:layout_width="wrap_content"
android:layout_height="wrap_content"
class="android.support.v4.view.ViewPager"
android:layout_alignParentStart="true"
android:id="#+id/view_pager"
android:layout_below="#+id/tab_layout" />
</RelativeLayout>
The classes for the tab fragments which are supposed to be displayed in the ViewPager are just normal auto generated Android Studio fragment classes.
One of the fragments:
public class CasualStats extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CasualStats() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CasualStats.
*/
// TODO: Rename and change types and number of parameters
public static CasualStats newInstance(String param1, String param2) {
CasualStats fragment = new CasualStats();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_casual_stats, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
The xml:
<RelativeLayout 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.app.anzel.r6s.CasualStats">
<!-- TODO: Update blank fragment layout -->
<TextView
android:text="1st fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="28dp"
android:layout_marginTop="22dp"
android:id="#+id/textView"
android:visibility="visible" />
</RelativeLayout>
The problem is that you have nested fragments and use getFragmentManager(); You should use getChildFragmentManager() instead.
java:
viewPagerAdapter = new PagerAdapter(getChildFragmentManager())
kotlin:
viewPagerAdapter = PagerAdapter(childFragmentManager)
I feel kind of stupid. The problem was with the ViewPager as I suspected. After 3h of code debugging I just moved the ViewPager from the layout with the tabs to another layout which basically connects all of the layouts.
The below sample code is working fine with viewpager and tabs. Try it out.
Main activity layout
<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.AppBarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tab_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="?attr/actionBarSize" />
<include layout="#layout/content_main" />
<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" />
Then viewpager container layout
<?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:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
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.test.myapplication.MainActivity"
tools:showIn="#layout/app_bar_main">
<android.support.v4.view.ViewPager
android:id="#+id/page_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000" />
</RelativeLayout>
And here is the main activity part:
package com.test.myapplication;
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.*;
import android.support.v4.app.Fragment;
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.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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 pager = (ViewPager)findViewById(R.id.page_container);
pager.setAdapter(new Adapter(getSupportFragmentManager()));
TabLayout tabs = (TabLayout)findViewById(R.id.tab_container);
tabs.setupWithViewPager(pager, true);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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.nav_camera) {
// Handle the camera action
} 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) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public static class Adapter extends FragmentStatePagerAdapter {
private String[] titles = new String[] {"ONE", "TWO"};
public Adapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new com.test.myapplication.Fragment();
case 1:
return new Fragment1();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
If you are using any tablayout with viewpager inside NestedScrollView, make sure to put android:fillViewport="true"
Reference in the nested scrollview. Note that, if you are working with navigation drawer, your fragment may not have a nested scrollview, but your activity fragment container maybe inside a nested scroll view. Because even an empty layout with a background color (for debugging the issue) does not show up, so it was not the problem of view pager in my case, it was the problem with nested scroll view.
Debugging tip: Instead of viewpager, put some layout and set a
background color to see if the layout is visible. If the layout itself
is not visible, then you have issue with the parent layout, most
probably NestedScrollView.
You are missing setupWithViewPager, and you don't need setOnTabSelectedListener:
tab_layout.setupWithViewPager(viewPager)
Let's look here:
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
You have to override also getPageTitle in adapter and there return tab title.
Last, don't use <view ..class> in xml, create normal xml view:
<android.support.v4.view.ViewPager
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/view_pager"
android:layout_below="#+id/tab_layout"/>
try this:
in your layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/tab_layout">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:id="#+id/view_pager"
android:layout_below="#+id/tab_layout" />
</RelativeLayout>
in activity:
TabLayout tab_layout = (TabLayout) findViewById(R.id.tab_layout);
tab_layout.addTab(tab_layout.newTab().setText("CASUAL"));
tab_layout.addTab(tab_layout.newTab().setText("RANKED"));
tab_layout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tab_layout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);
tab_layout.post(new Runnable() {
#Override
public void run() {
tab_layout.setupWithViewPager(viewPager);
}
});
tab_layout.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) {
}
});
PagerAdapter :
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
// an array of tab titles
private String tabTitles[] = new String[]{"CASUAL", "RANKED"};
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
CasualStats tab1 = new CasualStats();
return tab1;
case 1:
RankedStats tab2 = new RankedStats();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
Related
Below is my code. Am having a navigation drawer and on click event not working. On clicking on it am having a fragment to load. But its not working.Am having both sliding menu and Tab layout. Does that make any issues?
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
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.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
public static int navItemIndex = 0;
private NavigationView navigationView;
private DrawerLayout drawer;
private static final String TAG_SOUP = "Soups";
private static final String TAG_SALADS = "Salads";
private static final String TAG_MAINCRSE = "Main Course";
private static final String TAG_BRKDIN = "Tiffin | Breakfast | Dinner";
private static final String TAG_SNACKS = "Snacks";
private static final String TAG_BEVERAGES = "Beverages";
public static String CURRENT_TAG = TAG_SOUP;
private FloatingActionButton fab;
private Handler mHandler;
private boolean shouldLoadHomeFragOnBackPress = true;
private View navHeader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
// navigationView.setNavigationItemSelectedListener(this);
navHeader = navigationView.getHeaderView(0);
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
//CURRENT_TAG = TAG_SOUP;
loadHomeFragment();
}
viewPager = (ViewPager) findViewById(R.id.pager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// set toolbar title
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
toggleFab();
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
//fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new SoupFragment(), TAG_SOUP);
adapter.addFragment(new SaladFragment(), TAG_SALADS);
adapter.addFragment(new MainCoursesFragment(), TAG_MAINCRSE);
adapter.addFragment(new TifBrkDinFragment(), TAG_BRKDIN);
adapter.addFragment(new SnacksFragment(), TAG_SNACKS);
adapter.addFragment(new BeveragesFragments(), TAG_BEVERAGES);
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);
}
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_SOUP;
loadHomeFragment();
return;
}
}
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);
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// soup
SoupFragment soupFragment = new SoupFragment();
return soupFragment;
case 1:
// salads
SaladFragment saladFragment = new SaladFragment();
return saladFragment;
case 2:
// Main courses
MainCoursesFragment mainCoursesFragment = new MainCoursesFragment();
return mainCoursesFragment;
case 3:
// Breakfast | Tiffin | Dinner
TifBrkDinFragment tifBrkDinFragment = new TifBrkDinFragment();
return tifBrkDinFragment;
case 4:
// Snacks
SnacksFragment snacksFragment = new SnacksFragment();
return snacksFragment;
case 5:
// Beverages
BeveragesFragments beveragesFragments = new BeveragesFragments();
return beveragesFragments;
default:
return new SaladFragment();
}
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.nav_soup:
navItemIndex = 0;
CURRENT_TAG = TAG_SOUP;
break;
case R.id.nav_salads:
navItemIndex = 1;
CURRENT_TAG = TAG_SALADS;
break;
case R.id.nav_main_course:
navItemIndex = 2;
CURRENT_TAG = TAG_MAINCRSE;
break;
case R.id.nav_brktifdin:
navItemIndex = 3;
CURRENT_TAG = TAG_BRKDIN;
break;
case R.id.nav_snacks:
navItemIndex = 4;
CURRENT_TAG = TAG_SNACKS;
break;
case R.id.nav_beverages:
// launch new intent instead of loading fragment
// startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
// drawer.closeDrawers();
navItemIndex = 5;
CURRENT_TAG = TAG_BEVERAGES;
break;
default:
navItemIndex = 0;
}
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
}
// show or hide the fab
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_soup:
fragment = new SoupFragment();
break;
case R.id.nav_salads:
fragment = new SaladFragment();
break;
case R.id.nav_main_course:
fragment = new MainCoursesFragment();
break;
case R.id.nav_brktifdin:
fragment = new TifBrkDinFragment();
break;
case R.id.nav_snacks:
fragment = new SnacksFragment();
break;
case R.id.nav_beverages:
fragment = new BeveragesFragments();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
Try below code ...!
MainActivity.java
package co.in.example.app.tab;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
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.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
Toolbar toolbar;
NavigationView navigationView;
protected TabFragment tabFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
tabFragment = new TabFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, tabFragment).commit();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
tabFragment.viewPager.setCurrentItem(0);
} else if (id == R.id.nav_gallery) {
tabFragment.viewPager.setCurrentItem(1);
} else if (id == R.id.nav_slideshow) {
tabFragment.viewPager.setCurrentItem(2);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
TabFragment.java
package co.in.example.app.tab;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class TabFragment extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
public TabHost tabHost;
private int currentTab = 0;
public ViewPager viewPager;
protected TabPagerAdapter pageAdapter;
private List<Fragment> fragments;
#SuppressWarnings("unchecked")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tabhost, null);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
tabHost = (TabHost) view.findViewById(android.R.id.tabhost);
viewPager.addOnPageChangeListener(this);
viewPager.setOffscreenPageLimit(3);
fragments = new ArrayList<Fragment>();
fragments.add(new FragmentImport());
fragments.add(new FragmentGallery());
fragments.add(new FragmentSlideShow());
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
pageAdapter = new TabPagerAdapter(getChildFragmentManager(),
fragments, getArguments());
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.imports));
tabHost.addTab(newTab(R.string.gallery));
tabHost.addTab(newTab(R.string.slideshow));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
changeTextColor(i);
}
tabHost.setOnTabChangedListener(this);
tabHost.setCurrentTab(currentTab);
}
private TabSpec newTab(int tabValue) {
TabSpec tabSpec = tabHost.newTabSpec("");
tabSpec.setIndicator(getTabIndicator(tabHost.getContext(), tabValue));
//tabSpec.setIndicator(tabValue, null);
tabSpec.setContent(new Dummy(getActivity()));
return tabSpec;
}
private View getTabIndicator(Context context, int title) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_layout, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText(title);
return view;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
changeTextColor(i);
}
}
private void changeTextColor(int i) {
if (currentTab == i) {
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setTextColor(getActivity().getResources().getColor(R.color.white));
} else {
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setTextColor(getActivity().getResources().getColor(R.color.tab_un_select));
}
}
public class Dummy implements TabHost.TabContentFactory {
private Context context;
public Dummy(Context context) {
this.context = context;
}
#Override
public View createTabContent(String tag) {
return new View(context);
}
}
}
TabPagerAdapter.java
package co.in.example.app.tab;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.List;
public class TabPagerAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;
public TabPagerAdapter(FragmentManager fm, List<Fragment> fragments,
Bundle args) {
super(fm);
this.fragments = fragments;
this.args = args;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
// Create a fragments as you needs
FragmentGallery.java
package co.in.example.app.tab;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentGallery extends Fragment {
#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_fragment_gallery, container, false);
}
}
slide menu item
activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_camera"
android:icon="#drawable/ic_menu_camera"
android:title="#string/imports" />
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/gallery" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/slideshow" />
</group>
</menu>
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
app:srcCompat="#android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<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" />
<FrameLayout 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/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="co.in.example.app.tab.MainActivity"
tools:showIn="#layout/activity_main" />
</LinearLayout>
<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>
tab_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_gravity="center"
android:layout_marginBottom="2dp"
android:gravity="center"
android:maxLines="1"
android:textSize="14sp" />
</LinearLayout>
tabhost.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#color/actionbar_bg"
android:fadingEdge="none"
android:gravity="center"
android:showDividers="none"
android:paddingTop="5dip"
android:tabStripEnabled="false" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#FFFFFF" />
</LinearLayout>
</TabHost>
// Create fragment xml file
fragment_fragment_import.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="co.in.example.app.tab.FragmentImport">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Import" />
</FrameLayout>
Actually i new in Android and got stuck in Navigation Drawer..
i have successfully designed material designed navigation drawer and their menu items .
But when i clicked on that menu it open a independent fragment while i want it to open it in particular tabs inside Tab Layout.
i have made separate Tab layout with custom Adapter. mytablayout .xml file is as
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabGravity="fill"
app:tabMode="fixed"
app:elevation="0dp"
android:background="#6ec6c5"
app:tabIndicatorColor="#000000"
app:tabSelectedTextColor="#color/textColor"
app:tabTextColor="#A8DCDC"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
my Tabfragment class are there:
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.fragment_tab, null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager(),int_items ));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
}
MyAdapter is :
public class MyAdapter extends FragmentPagerAdapter {
int int_items;
public MyAdapter(FragmentManager fm,int int_items) {
super(fm);
this.int_items = int_items;
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new ProductFragment();
case 1 : return new ProductFragment();
case 2 : return new ProductFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "PRODUCTS";
case 1 :
return "FEATURED";
case 2 :
return "FAVOURITES";
}
return null;
}
}
My SplitviewActivity is shown like this:
public class SplitViewActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private NavigationView navigationView;
FragmentManager mFragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_split_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new TabFragment()).commit();
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.navigation_item_products:
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new TabFragment()).commit();
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
// updateDisplay(new AttachmentFragment());
break;
case R.id.navigation_item_new_Releases:
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new ProductFragment()).commit();
/* FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container,new ProductFragment()).commit();*/
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
// updateDisplay(new ImageFragment());
break;
case R.id.navigation_item_favorites:
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new TabFragment()).commit();
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
// updateDisplay(new MyLocationFragment());
break;
case R.id.navigation_item_about_us:
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
// updateDisplay(new MyLocationFragment());
break;
case R.id.navigation_item_notification:
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
// updateDisplay(new MyLocationFragment());
break;
case R.id.navigation_sub_item_01:
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 01 Clicked", Toast.LENGTH_SHORT).show();
break;
case R.id.navigation_sub_item_02:
Toast.makeText(SplitViewActivity.this, "Navigation Sub Item 02 Clicked", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
}
#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_splash_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
}
my navigation menu item.xml file are as :
<?xml version="1.0" encoding="utf-8"?>
<group android:checkableBehavior="single">
<item
android:id="#+id/navigation_item_products"
android:checked="true"
android:title="Products" />
<item
android:id="#+id/navigation_item_new_Releases"
android:title="New Releases" />
<item
android:id="#+id/navigation_item_favorites"
android:title="favorites" />
<item
android:id="#+id/navigation_item_about_us"
android:title="About Us" />
<item
android:id="#+id/navigation_item_notification"
android:title="Notifications" />
</group>
<item android:title="">
<menu>
<item
android:id="#+id/navigation_sub_item_01"
android:title="Configure" />
<item
android:id="#+id/navigation_sub_item_02"
android:title="Logout" />
</menu>
</item>
Everything is work fine except.All three tabs has been Shown.navigation drawer also work well.
Only thing that i couldn't understand that how can i open a fragment in tab on click of navigation menuitems.At present when i click on menu item,it open an independent fragment not in tab.How can i achieve this ..Any help would be Appreciated in advanced..
just check on drawer onClick the clicked position and check against each viewpager tabs which tab is what u want and use Viewpager.setCurrentItem(posiition)
to navigate to that tab.
public void setStartTab(String topTab) {
LocalLog.e("TOPTAB",topTab+"");
if(topTab==null){
mViewPager.setCurrentItem(0);
}else{
for(int i=0;i<mTabs.size();i++){
LocalLog.e("TOPTAB",mTabs.get(i).name);
if(mTabs.get(i).name.equalsIgnoreCase(topTab)){
LocalLog.e("TOPTAB",i+"true");
mViewPager.setCurrentItem(i);
}
}
}
}
activity_main.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<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.support.design.widget.AppBarLayout>
<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" />
MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
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);
}
}
}
its works for me
I have written a simple code with navigation drawer and 3 fixed tabs but i facing these two bugs
1> Even when the navigation drawer is open and when i click on it... The tabs which are present at the same spot hidden behind the navigation drawer get clicked as well.
2> When i click the items on navigation drawer... the action get performed but the fragment is not replaced or more precisely hidden by the viewpager.
Here are the codes..
MainActivity.java
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
//getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TabOne(), getString(R.string.tabOne));
adapter.addFragment(new TabTwo(), getString(R.string.tabTwo));
adapter.addFragment(new TabThree(), getString(R.string.tabThree));
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 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;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
ActivityMain.xml
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<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.support.design.widget.AppBarLayout>
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<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" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.coastallabs.chat.devchat.activity.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
In your fragment_navigation_drawer.xml:
set rootview clickable = true.
My app has a navigation drawer with a few items and have 2 swipeable views. My question is, how can I make those swipeable views have different title and content depending on what navigation drawer item I click on. Currently I click on any navigation drawer item it displays the same swipeable views.
Please let me know if you need some clarification or something. Thanks!
Edit: Just so I'm clear. I don't mean swipeable views inside the nav drawer. When I tap on the nav drawer item, it takes me to that layout.
EDIT:
MainActivity.java
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
//Pager
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"Home", "Events"};
int Numboftabs = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
// 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.tabsScrollColor);
}
});
// 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;
}
/*
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action selected", Toast.LENGTH_SHORT).show();
}
*/
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new ArithmeticFragment();
title = getString(R.string.nav_item_arithmetic);
break;
case 1:
fragment = new AreaFragment();
title = getString(R.string.nav_item_area);
break;
case 2:
fragment = new ProbabilityFragment();
title = getString(R.string.nav_item_probability);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
activity_main.xml
<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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar" />
<model.SlidingTabLayout
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:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="activity.FragmentDrawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
tab_1.xml (pretty much the same as tab_2.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="You Are In Tab 1"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
NavDrawerItem.java
public class NavDrawerItem {
private boolean showNotify;
private String title;
public NavDrawerItem() {
}
public NavDrawerItem(boolean showNotify, String title) {
this.showNotify = showNotify;
this.title = title;
}
public boolean isShowNotify() {
return showNotify;
}
public void setShowNotify(boolean showNotify) {
this.showNotify = showNotify;
}
public String getTitle() {
return title;
}
public void setTitle(String title){
this.title = title;
}
}
NavigationDrawerAapter.java
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
}
}
}
ViewPagerAdapter.java
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
{
Tab1 tab1 = new Tab1();
return tab1;
}
else // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
Tab2 tab2 = new Tab2();
return tab2;
}
}
// 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;
}
}
Follow this link. It has your exact requirements. The following functions should be useful for you. Try it out. It handles navigation drawer, and navigation drawer item clicks.
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
and
private void selectItem(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
switch (position) {
case 0:
ft.replace(R.id.content_frame, new Fragment1, Constants.TAG_FRAGMENT).commit();
break;
case 1:
ft.replace(R.id.content_frame, new Fragment2, Constants.TAG_FRAGMENT);
ft.commit();
break;
}
mDrawerList.setItemChecked(position, true);
setTitle(title[position]);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
I'm trying to get the new TabLayout in the android design library working.
I'm following this post:
http://android-developers.blogspot.com/2015/05/android-design-support-library.html
and the documentation:
http://developer.android.com/reference/android/support/design/widget/TabLayout.html
And have come up with the following code in my activity but the tablayout isn't showing up when I run the activity.
I tried adding in the activity layout file, but it says it can't find that xml tag.
public class TabActivity extends BaseActivity {
SectionPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
LinearLayout v = (LinearLayout)findViewById(R.id.tabContainer);
TabLayout tabLayout = new TabLayout(this);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setLayoutParams(new LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 50));
v.addView(tabLayout);
mSectionsPagerAdapter = new SectionPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
private String TAG = "SectionPagerAdapter";
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
return new Fragment();
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "test";
case 1:
return "test";
case 2:
}
return null;
}
}
}
Added the following to my gradle file
compile 'com.android.support:design:22.2.0'
I've just managed to setup new TabLayout, so here are the quick steps to do this (ノ◕ヮ◕)ノ*:・゚✧
Add dependencies inside your build.gradle file:
dependencies {
compile 'com.android.support:design:23.1.1'
}
Add TabLayout inside your layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Setup your Activity like this:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
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.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class TabLayoutActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pull_to_refresh);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FirstTabFragment();
case 1:
default:
return new SecondTabFragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "First Tab";
case 1:
default:
return "Second Tab";
}
}
}
}
I had to collect information from various sources to put together a functioning TabLayout. The following is presented as a complete use case that can be modified as needed.
Make sure the module build.gradle file contains a dependency on com.android.support:design.
dependencies {
compile 'com.android.support:design:23.1.1'
}
In my case, I am creating an About activity in the application with a TabLayout. I added the following section to AndroidMainifest.xml. Setting the parentActivityName allows the home arrow to take the user back to the main activity.
<!-- android:configChanges="orientation|screenSize" makes the activity not reload when the orientation changes. -->
<activity
android:name=".AboutActivity"
android:label="#string/about_app"
android:theme="#style/MyApp.About"
android:parentActivityName=".MainActivity"
android:configChanges="orientation|screenSize" >
<!-- android.support.PARENT_ACTIVITY is necessary for API <= 15. -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
styles.xml contains the following entries. This app has a white AppBar for the main activity and a blue AppBar for the About activity. We need to set colorPrimaryDark for the About activity so that the status bar above the AppBar is blue.
<style name="MyApp" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorAccent">#color/blue</item>
</style>
<style name="MyApp.About" />
<!-- ThemeOverlay.AppCompat.Dark.ActionBar" makes the text and the icons in the AppBar white. -->
<style name="MyApp.DarkAppBar" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="MyApp.AppBarOverlay" parent="ThemeOverlay.AppCompat.ActionBar" />
<style name="MyApp.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
There is also a styles.xml (v19). It is located at src/main/res/values-v19/styles.xml. This file is only applied if the API of the device is >= 19.
<!-- android:windowTranslucentStatus requires API >= 19. It makes the system status bar transparent.
When it is specified the root layout should include android:fitsSystemWindows="true".
colorPrimaryDark goes behind the status bar, which is then darkened by the overlay. -->
<style name="MyApp.About">
<item name="android:windowTranslucentStatus">true</item>
<item name="colorPrimaryDark">#color/blue</item>
</style>
AboutActivity.java contains the following code. In my case I have a fixed number of tabs (7) so I could remove all the code dealing with dynamic tabs.
import android.os.Bundle;
import android.support.design.widget.TabLayout;
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.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class AboutActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about_coordinatorlayout);
// We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
Toolbar supportAppBar = (Toolbar) findViewById(R.id.about_toolbar);
setSupportActionBar(supportAppBar);
// Display the home arrow on supportAppBar.
final ActionBar appBar = getSupportActionBar();
assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that appBar might be null.
appBar.setDisplayHomeAsUpEnabled(true);
// Setup the ViewPager.
ViewPager aboutViewPager = (ViewPager) findViewById(R.id.about_viewpager);
assert aboutViewPager != null; // This assert removes the incorrect warning in Android Studio on the following line that aboutViewPager might be null.
aboutViewPager.setAdapter(new aboutPagerAdapter(getSupportFragmentManager()));
// Setup the TabLayout and connect it to the ViewPager.
TabLayout aboutTabLayout = (TabLayout) findViewById(R.id.about_tablayout);
assert aboutTabLayout != null; // This assert removes the incorrect warning in Android Studio on the following line that aboutTabLayout might be null.
aboutTabLayout.setupWithViewPager(aboutViewPager);
}
public class aboutPagerAdapter extends FragmentPagerAdapter {
public aboutPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
// Get the count of the number of tabs.
public int getCount() {
return 7;
}
#Override
// Get the name of each tab. Tab numbers start at 0.
public CharSequence getPageTitle(int tab) {
switch (tab) {
case 0:
return getString(R.string.version);
case 1:
return getString(R.string.permissions);
case 2:
return getString(R.string.privacy_policy);
case 3:
return getString(R.string.changelog);
case 4:
return getString(R.string.license);
case 5:
return getString(R.string.contributors);
case 6:
return getString(R.string.links);
default:
return "";
}
}
#Override
// Setup each tab.
public Fragment getItem(int tab) {
return AboutTabFragment.createTab(tab);
}
}
}
AboutTabFragment.java is used to populate each tab. In my case, the first tab has a LinearLayout inside of a ScrollView and all the others have a WebView as the root layout.
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;
public class AboutTabFragment extends Fragment {
private int tabNumber;
// AboutTabFragment.createTab stores the tab number in the bundle arguments so it can be referenced from onCreate().
public static AboutTabFragment createTab(int tab) {
Bundle thisTabArguments = new Bundle();
thisTabArguments.putInt("Tab", tab);
AboutTabFragment thisTab = new AboutTabFragment();
thisTab.setArguments(thisTabArguments);
return thisTab;
}
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Store the tab number in tabNumber.
tabNumber = getArguments().getInt("Tab");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View tabLayout;
// Load the about tab layout. Tab numbers start at 0.
if (tabNumber == 0) {
// Setting false at the end of inflater.inflate does not attach the inflated layout as a child of container.
// The fragment will take care of attaching the root automatically.
tabLayout = inflater.inflate(R.layout.about_tab_version, container, false);
} else { // load a WebView for all the other tabs. Tab numbers start at 0.
// Setting false at the end of inflater.inflate does not attach the inflated layout as a child of container.
// The fragment will take care of attaching the root automatically.
tabLayout = inflater.inflate(R.layout.about_tab_webview, container, false);
WebView tabWebView = (WebView) tabLayout;
switch (tabNumber) {
case 1:
tabWebView.loadUrl("file:///android_asset/about_permissions.html");
break;
case 2:
tabWebView.loadUrl("file:///android_asset/about_privacy_policy.html");
break;
case 3:
tabWebView.loadUrl("file:///android_asset/about_changelog.html");
break;
case 4:
tabWebView.loadUrl("file:///android_asset/about_license.html");
break;
case 5:
tabWebView.loadUrl("file:///android_asset/about_contributors.html");
break;
case 6:
tabWebView.loadUrl("file:///android_asset/about_links.html");
break;
default:
break;
}
}
return tabLayout;
}
}
about_coordinatorlayout.xml is as follows:
<!-- android:fitsSystemWindows="true" moves the AppBar below the status bar.
When it is specified the theme should include <item name="android:windowTranslucentStatus">true</item>
to make the status bar a transparent, darkened overlay. -->
<android.support.design.widget.CoordinatorLayout
android:id="#+id/about_coordinatorlayout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:fitsSystemWindows="true" >
<!-- the LinearLayout with orientation="vertical" moves the ViewPager below the AppBarLayout. -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- We need to set android:background="#color/blue" here or any space to the right of the TabLayout on large devices will be white. -->
<android.support.design.widget.AppBarLayout
android:id="#+id/about_appbarlayout"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/blue"
android:theme="#style/MyApp.AppBarOverlay" >
<!-- android:theme="#style/PrivacyBrowser.DarkAppBar" makes the text and icons in the AppBar white. -->
<android.support.v7.widget.Toolbar
android:id="#+id/about_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/blue"
android:theme="#style/MyApp.DarkAppBar"
app:popupTheme="#style/MyApp.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/about_tablayout"
xmlns:android.support.design="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android.support.design:tabBackground="#color/blue"
android.support.design:tabTextColor="#color/light_blue"
android.support.design:tabSelectedTextColor="#color/white"
android.support.design:tabIndicatorColor="#color/white"
android.support.design:tabMode="scrollable" />
</android.support.design.widget.AppBarLayout>
<!-- android:layout_weight="1" makes about_viewpager fill the rest of the screen. -->
<android.support.v4.view.ViewPager
android:id="#+id/about_viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
about_tab_version.xml is as follows:
<!-- The ScrollView allows the LinearLayout to scroll if it exceeds the height of the page. -->
<ScrollView
android:id="#+id/about_version_scrollview"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent" >
<LinearLayout
android:id="#+id/about_version_linearlayout"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:padding="16dp" >
<!-- Include whatever content you want in this tab here. -->
</LinearLayout>
</ScrollView>
And about_tab_webview.xml:
<!-- This WebView displays inside of the tabs in AboutActivity. -->
<WebView
android:id="#+id/about_tab_webview"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" />
There are also entries in strings.xml
<string name="about_app">About App</string>
<string name="version">Version</string>
<string name="permissions">Permissions</string>
<string name="privacy_policy">Privacy Policy</string>
<string name="changelog">Changelog</string>
<string name="license">License</string>
<string name="contributors">Contributors</string>
<string name="links">Links</string>
And colors.xml
<color name="blue">#FF1976D2</color>
<color name="light_blue">#FFBBDEFB</color>
<color name="white">#FFFFFFFF</color>
src/main/assets contains the HTML files referenced in AboutTabFragemnt.java.
I try to solve here is my code.
first add dependency in build.gradle(app).
dependencies {
compile 'com.android.support:design:23.1.1'
}
Create PagerAdapter.class
public class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
Log.i("PosTabItem",""+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) {
Log.i("PosTab",""+position);
return mFragmentTitleList.get(position);
}
}
create activity_main.xml
<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:id="#+id/main_layout"
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>
create MainActivity.class
public class MainActivity extends AppCompatActivity {
Pager pager;
#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);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
pager = new Pager(getSupportFragmentManager());
pager.addFragment(new FragmentOne(), "One");
viewPager.setAdapter(pager);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setSmoothScrollingEnabled(true);
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) {
}
});
}
}
and finally create fragment to add in viewpager
crate fragment_one.xml
<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:text="Location"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Create FragmentOne.class
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container,false);
return view;
}
}
I am facing some issue with menu change when fragment changes in ViewPager. I ended up implemented below code.
DashboardFragment
public class DashboardFragment extends BaseFragment {
private Context mContext;
private TabLayout mTabLayout;
private ViewPager mViewPager;
private DashboardPagerAdapter mAdapter;
private OnModuleChangeListener onModuleChangeListener;
private NavDashBoardActivity activityInstance;
public void setOnModuleChangeListener(OnModuleChangeListener onModuleChangeListener) {
this.onModuleChangeListener = onModuleChangeListener;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.dashboard_fragment, container, false);
}
//pass -1 if you want to get it via pager
public Fragment getFragmentFromViewpager(int position) {
if (position == -1)
position = mViewPager.getCurrentItem();
return ((Fragment) (mAdapter.instantiateItem(mViewPager, position)));
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mContext = getActivity();
activityInstance = (NavDashBoardActivity) getActivity();
mTabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
final List<EnumUtils.Module> moduleToShow = getModuleToShowList();
mViewPager.setOffscreenPageLimit(moduleToShow.size());
for(EnumUtils.Module module :moduleToShow)
mTabLayout.addTab(mTabLayout.newTab().setText(EnumUtils.Module.getTabText(module)));
updateTabPagerAndMenu(0 , moduleToShow);
mAdapter = new DashboardPagerAdapter(getFragmentManager(),moduleToShow);
mViewPager.setOffscreenPageLimit(mAdapter.getCount());
mViewPager.setAdapter(mAdapter);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(final TabLayout.Tab tab) {
mViewPager.post(new Runnable() {
#Override
public void run() {
mViewPager.setCurrentItem(tab.getPosition());
}
});
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//added to redraw menu on scroll
}
#Override
public void onPageSelected(int position) {
updateTabPagerAndMenu(position , moduleToShow);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
//also validate other checks and this method should be in SharedPrefs...
public static List<EnumUtils.Module> getModuleToShowList(){
List<EnumUtils.Module> moduleToShow = new ArrayList<>();
moduleToShow.add(EnumUtils.Module.HOME);
moduleToShow.add(EnumUtils.Module.ABOUT);
return moduleToShow;
}
public void setCurrentTab(final int position){
if(mViewPager != null){
mViewPager.postDelayed(new Runnable() {
#Override
public void run() {
mViewPager.setCurrentItem(position);
}
},100);
}
}
private Fragment getCurrentFragment(){
return mAdapter.getCurrentFragment();
}
private void updateTabPagerAndMenu(int position , List<EnumUtils.Module> moduleToShow){
//it helps to change menu on scroll
//http://stackoverflow.com/a/27984263/3496570
//No effect after changing below statement
ActivityCompat.invalidateOptionsMenu(getActivity());
if(mTabLayout != null)
mTabLayout.getTabAt(position).select();
if(onModuleChangeListener != null){
if(activityInstance != null){
activityInstance.updateStatusBarColor(
EnumUtils.Module.getStatusBarColor(moduleToShow.get(position)));
}
onModuleChangeListener.onModuleChanged(moduleToShow.get(position));
mTabLayout.setSelectedTabIndicatorColor(EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
mTabLayout.setTabTextColors(ContextCompat.getColor(mContext,android.R.color.black)
, EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
}
}
}
dashboardfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- our tablayout to display tabs -->
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabBackground="#android:color/white"
app:tabGravity="fill"
app:tabIndicatorHeight="4dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="#android:color/black"
app:tabTextColor="#android:color/black" />
<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
DashboardPagerAdapter
public class DashboardPagerAdapter extends FragmentPagerAdapter {
private List<EnumUtils.Module> moduleList;
private Fragment mCurrentFragment = null;
public DashboardPagerAdapter(FragmentManager fm, List<EnumUtils.Module> moduleList){
super(fm);
this.moduleList = moduleList;
}
#Override
public Fragment getItem(int position) {
return EnumUtils.Module.getDashboardFragment(moduleList.get(position));
}
#Override
public int getCount() {
return moduleList.size();
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (getCurrentFragment() != object) {
mCurrentFragment = ((Fragment) object);
}
super.setPrimaryItem(container, position, object);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
public int getModulePosition(EnumUtils.Module moduleName){
for(int x = 0 ; x < moduleList.size() ; x++){
if(moduleList.get(x).equals(moduleName))
return x;
}
return -1;
}
}
And in each page of Fragment setHasOptionMenu(true) in onCreate and implement onCreateOptionMenu. then it will work properly.
dASHaCTIVITY
public class NavDashBoardActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Context mContext;
private DashboardFragment dashboardFragment;
private Toolbar mToolbar;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_dash_board);
mContext = NavDashBoardActivity.this;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(ContextCompat.getColor(mContext,R.color.yellow_action_bar));
}
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
updateToolbarText(new ToolbarTextBO("NCompass " ,""));
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//onclick of back button on Navigation it will popUp fragment...
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!toggle.isDrawerIndicatorEnabled()) {
getSupportFragmentManager().popBackStack();
}
}
});
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);//It helps to show icon on Navigation
updateNavigationMenuItem(navigationView);
navigationView.setNavigationItemSelectedListener(this);
//Left Drawer Upper Section
View headerLayout = navigationView.getHeaderView(0); // 0-index header
TextView userNameTv = (TextView) headerLayout.findViewById(R.id.tv_user_name);
userNameTv.setText(AuthSharePref.readUserLoggedIn().getFullName());
RoundedImageView ivUserPic = (RoundedImageView) headerLayout.findViewById(R.id.iv_user_pic);
ivUserPic.setImageResource(R.drawable.profile_img);
headerLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//close drawer and add a fragment to it
drawer.closeDrawers();//also try other methods..
}
});
//ZA code starts...
dashboardFragment = new DashboardFragment();
dashboardFragment.setOnModuleChangeListener(new OnModuleChangeListener() {
#Override
public void onModuleChanged(EnumUtils.Module module) {
if(mToolbar != null){
mToolbar.setBackgroundColor(EnumUtils.Module.getModuleColor(module));
if(EnumUtils.Module.getMenuID(module) != -1)
navigationView.getMenu().findItem(EnumUtils.Module.getMenuID(module)).setChecked(true);
}
}
});
addBaseFragment(dashboardFragment);
backStackListener();
}
public void updateStatusBarColor(int colorResourceID){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(colorResourceID);
}
}
private void updateNavigationMenuItem(NavigationView navigationView){
List<EnumUtils.Module> modules = DashboardFragment.getModuleToShowList();
if(!modules.contains(EnumUtils.Module.MyStores)){
navigationView.getMenu().findItem(R.id.nav_my_store).setVisible(false);
}
if(!modules.contains(EnumUtils.Module.Livewall)){
navigationView.getMenu().findItem(R.id.nav_live_wall).setVisible(false);
}
}
private void backStackListener(){
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() >= 1)
{
toggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
toggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp); //set your own
///toggle.setDrawerArrowDrawable();
///toggle.setDrawerIndicatorEnabled(false); // this will hide hamburger image
///Toast.makeText(mContext,"Update to Arrow",Toast.LENGTH_SHORT).show();
}
else{
toggle.setDrawerIndicatorEnabled(true);
}
if(getSupportFragmentManager().getBackStackEntryCount() >0){
if(getCurrentFragment() instanceof DashboardFragment){
Fragment subFragment = ((DashboardFragment) getCurrentFragment())
.getViewpager(-1);
}
}
else{
}
}
});
}
private void updateToolBarTitle(String title){
getSupportActionBar().setTitle(title);
}
public void updateToolBarColor(String hexColor){
if(mToolbar != null)
mToolbar.setBackgroundColor(Color.parseColor(hexColor));
}
#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) {
if (drawer.isDrawerOpen(GravityCompat.START))
getMenuInflater().inflate(R.menu.empty, menu);
return super.onCreateOptionsMenu(menu);//true is wriiten first..
}
#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();
if (id == android.R.id.home)
{
if (drawer.isDrawerOpen(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
} else
drawer.openDrawer(GravityCompat.START);
}
return false;///true;
}
return false;// false so that fragment can also handle the menu event. Otherwise it is handled their
///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.nav_my_store) {
// Handle the camera action
dashboardFragment.setCurrentTab(EnumUtils.Module.MyStores);
}
}else if (id == R.id.nav_log_out) {
Dialogs.logOut(mContext);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void updateToolbarText(ToolbarTextBO toolbarTextBO){
mToolbar.setTitle("");
mToolbar.setSubtitle("");
if(toolbarTextBO.getTitle() != null && !toolbarTextBO.getTitle().isEmpty())
mToolbar.setTitle(toolbarTextBO.getTitle());
if(toolbarTextBO.getDescription() != null && !toolbarTextBO.getDescription().isEmpty())
mToolbar.setSubtitle(toolbarTextBO.getDescription());*/
}
#Override
public void onPostCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
}
<?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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".ui.MainActivity"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<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/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
>
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_3" />
<android.support.design.widget.TabItem
android:id="#+id/tItemab4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_4" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tabs"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:ignore="NotSibling"/>
</android.support.constraint.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.MainActivity">
<include layout="#layout/tabs"></include>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="#dimen/activity_vertical_margin"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
android:layout_marginTop="80dp">
<FrameLayout android:id="#+id/tabContent"
android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp">
</FrameLayout>
</LinearLayout>
</RelativeLayout>
public class MainActivity extends AppCompatActivity{
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPagerAdapter adapter;
private final static int[] tabIcons = {
R.drawable.ic_action_car,
android.R.drawable.ic_menu_mapmode,
android.R.drawable.ic_dialog_email,
R.drawable.ic_action_settings
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new CarFragment());
adapter.addFrag(new LocationFragment());
adapter.addFrag(new MessageFragment());
adapter.addFrag(new SettingsFragment());
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
void addFrag(Fragment fragment) {
mFragmentList.add(fragment);
}
}
}
So easy way :
XML:
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Java code:
private ViewPager viewPager;
private String[] PAGE_TITLES = new String[]{
"text1",
"text1",
"text3"
};
private final Fragment[] PAGES = new Fragment[]{
new fragment1(),
new fragment2(),
new fragment3()
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_a_requests);
/**TODO ***************tebLayout*************************/
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#1f57ff"));
tabLayout.setSelectedTabIndicatorHeight((int) (4 *
getResources().getDisplayMetrics().density));
tabLayout.setTabTextColors(Color.parseColor("#9d9d9d"),
Color.parseColor("#0d0e10"));
tabLayout.setupWithViewPager(viewPager);
/***************************************************************************/
}
Add this to the module build.gradle:
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'