View pager With Fragments and Indicator - android

I am developing an app in which I have implemented ViewPager I want the user to swipe and get the next screen. I am implementing fragments. All is well but I want one more thing. I want to indicate which screen is active now, just like tabs. I searched over the internet but did not find any thing helpful. If there is an idea that would be appriciated.
Here is my view pager adapter and fragment activity and xml layout
import java.util.ArrayList;
import java.util.List;
import com.viewpagerindicator.TitlePageIndicator;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements OnPageChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Fragment> list = new ArrayList<Fragment>();
list.add(MyFragment.newInstance("fragment 1"));
list.add(MyFragment.newInstance("fragment 2"));
list.add(MyFragment.newInstance("fragment 3"));
MyPagerAdapter a = new MyPagerAdapter(getSupportFragmentManager(), list);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(a);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
}
adapter.java
package com.example.fragments;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.view.View;
public class MyPagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm,List<Fragment> f) {
super(fm);
this.fragments = f;
}
#Override
public Fragment getItem(int arg0) {
return fragments.get(arg0);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return fragments.size();
}
}
main.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" >
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_below="#+id/titles"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>

see for this I have created a class to create page indicator
public class DotsScrollBar
{
LinearLayout main_image_holder;
public static void createDotScrollBar(Context context, LinearLayout main_holder,int selectedPage,int count)
{
for(int i=0;i<count;i++)
{
ImageView dot = null;
dot= new ImageView(context);
LinearLayout.LayoutParams vp =
new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
dot.setLayoutParams(vp);
if(i==selectedPage)
{
try {
dot.setImageResource(R.drawable.paging_h);
} catch (Exception e)
{
Log.d("inside DotsScrollBar.java","could not locate identifier");
}
}else
{
dot.setImageResource(R.drawable.paging_n);
}
main_holder.addView(dot);
}
main_holder.invalidate();
}
}
now in your activity class call the function createDotScrollBar as below:
public void updateIndicator(int currentPage) {
dots_scrollbar_holder.removeAllViews();
DotsScrollBar.createDotScrollBar(this, mDotsScrollbarHolder,
mCurrentPage, totalNumberOfPages);
}
and call updateIndicator function inside onPageScrollStateChanged
like this :
#Override
public void onPageScrollStateChanged(int state) {
// TODO Auto-generated method stub
switch (state) {
case 0:
updateIndicator(mCurrentPage);
break;
}
hope this will do the trick.

You basically have three options:
1. Use the android native PagerTitleStrip
It's very easy to implement, simply add it as a child item to your ViewPager in the xml and define the gravity as TOP or BOTTOM like this:
<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" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</android.support.v4.view.ViewPager>
</RelativeLayout>
But to be honest it doesn't look very great and I can't say anything about backwards or forwards compatibility. The above was tested in API 17
2. Use a 3rd party library
Like the insanely good ViewPagerIndictor from Jake Wharton
3. Code an implementation of your own
Like suggested in the answer from shruti. Even in this case though I would recommend you to code alongside Jake Whartons example, it's really that amazing!

I created a library to address the need for a page indicator in a ViewPager. My library contains a View called DotIndicator. To use my library, add compile 'com.matthew-tamlin:sliding-intro-screen:3.2.0' to your gradle build file.
The View can be added to your layout by adding the following:
<com.matthewtamlin.sliding_intro_screen_library.indicators.DotIndicator
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:numberOfDots=YOUR_INT_HERE
app:selectedDotIndex=YOUR_INT_HERE/>
The above code perfectly replicates the functionality of the dots on the Google Launcher homescreen, however if you want to further customise it then the following attributes can be added:
app:unselectedDotDiameter and app:selectedDotDiameter to set the diameters of the dots
app:unselectedDotColor and app:selectedDotColor to set the colors of the dots
app:spacingBetweenDots to change the distance between the dots
app:dotTransitionDuration to set the time for animating the change from small to big (and back)
Additionally, the view can be created programatically using:
DotIndicator indicator = new DotIndicator(context);
Methods exist to modify the properties, similar to the attributes. To update the indicator to show a different page as selected, just call method indicator.setSelectedItem(int, true) from inside ViewPager.OnPageChangeListener.onPageSelected(int).
Here's an example of it in use:
If you're interested, the library was actually designed to make intro screens like the one shown in the above gif.
Github source available here: https://github.com/MatthewTamlin/SlidingIntroScreen

Related

ViewPager2 preloaing next fragment even when offsetlimit is the default(0)

I am facing this rather strange problem with viewPager2.
I did some reading and found out that viewPager2 has a default offset limit of 0 which is perfect for my application.
I'm using it with a tab layout and I have 3 fragments (Home, Profile, Notification).
When the activity loads and the first fragment(Home) loads, I can see in my logcat that the next fragment(Profile) is not loaded, as expected.
But when I click on the profile tab something strange happens, the next tab(Notification) is preloaded. The methods
onAttach,onCreate,onCreateView,onActivityCreated,onStart for the Notification tab is called.
Why is this doing so and how to I fix this ?
Logcat Screenshot
I have attached a screen shot of my logcat here.
Thankyou in advance.
I Assume you mean OFFSCREEN_PAGE_LIMIT_DEFAULT not offsetlimit as you are talking about a preloading of fragments problem.
And the default value is -1 not zero https://developer.android.com/reference/androidx/viewpager2/widget/ViewPager2.html#OFFSCREEN_PAGE_LIMIT_DEFAULT
and the default means
Value to indicate that the default caching mechanism of RecyclerView should be used instead of explicitly prefetch and retain pages to either side of the current page.
As this is a performance optimisation of the recyclerview, I would say it's not a guarantee that it won't preload your fragments, it's just left to the caching mechanism of the recyclerview to decide.
There are a number of factors that can affect the recyclerview's caching mechanism.
If preloading of your fragment is a problem because you have dynamic data in it that you only want to be loaded when the page is shown then it would be better to move your fragment to use a "lazy loading" method i.e. only load the data when it is shown.
I had a similar problem with the original viewpager and solved it with "lazy loading". If the timing of loading of your dynamic data is the problem then update the question and then I can outline a possible solution.
Update:3
It seems that Viewpager2 actually works correctly with the Fragments lifecycle unlike the original Viewpager thus you can call updateView() as shown in update2 example from the Fragments onResume method without having to use the pageSelected callback via the Adapter to trigger the update of the View.
Update:
I believe the actual cause from looking at the viewpager2 code is that selecting the Tab does a fake drag with smooth scrolling and smooth scrolling adds the selected item +1 to the cache, if you swipe from Tab0 to Tab1 yourself it does not create Tab2
ViewPager2 is a bit different and "lazy loading" method I used for the original ViewPager does not totally fit but there is a slightly different way to do the same.
The main idea with the original ViewPager was to update the view ONLY when a page was selected using a onPageChangeListener but ViewPager2 uses a callback instead
So add the following after you have created the ViewPager2 (in the Activity onCreate usually)
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// Tell the recyclerview that position 2 has changed when selected
// Thus it recreates it updating the dynamic data
if (position == 2) {
// the adapter for the ViewPager needs to a member of the Activity class so accessible here
adapter.notifyItemChanged(position);
}
}
});
This is simpler but has a minor drawback that the dynamic data is loaded when it is preloaded and then again when it is actually displayed.
Update2:
A more efficient addition to first method more similar to my original approach
This is a full working example as it is easier to explain.
The main idea is in your fragment with the dynamic data that you ONLY want to load when it is displayed is to create an empty "placeholder" view item and you don't fill it with data in the Fragments onViewCreated, in this example it is a second textview with no text but could be a recyclerview with zero objects or any other type of view.
In your Fragment you then create a method to update the "placeholder" with the data (in this case the method is called updateView() which sets the textview text to the current date and time)
Then in your Fragment Adapter you store a reference to each fragment it creates in a ArrayList (this allows you get the fragment back) and you then create an updateFragment() method in the adapter that uses the position to get the Fragment to be able to call the updateView() on it.
Finally again you use onPageSelected to call the updateFragment with the position you want to dynamically update.
So textview1 shows the data and time the fragement was created and textview2 is only shown on the third Tab and has a date and time on when page was selected. Note that texview1 on "Tab 2" and "Tab 3" is the same time when you click on the "Tab 2" headers to change tabs (this is the problem in the question)
MainActivity.java
package com.test.viewpager2;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager2 viewPager2;
ViewPager2Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager2 = findViewById(R.id.viewpager2);
tabLayout = findViewById(R.id.tabLayout);
viewPager2.setAdapter(createCardAdapter());
new TabLayoutMediator(tabLayout, viewPager2,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// Tell the recyclerview that position 2 has changed when selected
// Thus it recreates it updating the dynamic data
if (position == 2) {
adapter.updateFragment(position);
}
}
});
}
private ViewPager2Adapter createCardAdapter() {
adapter = new ViewPager2Adapter(this);
return adapter;
}
}
ViewPager2Adapter.java
package com.test.viewpager2;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import java.util.ArrayList;
public class ViewPager2Adapter extends FragmentStateAdapter {
private static final int numOfTabs = 3;
private ArrayList<Fragment> fragments = new ArrayList<>();
public ViewPager2Adapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull #Override public Fragment createFragment(int position){
Fragment fragment = TextFragment.newInstance(position);
fragments.add(fragment);
return fragment;
}
#Override
public int getItemCount(){
return numOfTabs;
}
public void updateFragment(int position){
Fragment fragment = fragments.get(position);
// Check fragment type to make sure it is one we know has an updateView Method
if (fragment instanceof TextFragment){
TextFragment textFragment = (TextFragment) fragment;
textFragment.updateView();
}
}
}
TextFragment.java
package com.test.viewpager2;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class TextFragment extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private int mParam1;
private View view;
public TextFragment() {
// Required empty public constructor
}
public static TextFragment newInstance(int param1) {
TextFragment fragment = new TextFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
Log.d("Frag", "newInstance");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getInt(ARG_PARAM1);
}
Log.d("Frag", "onCreate");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.d("Frag", "onCreateView");
view = inflater.inflate(R.layout.fragment_text, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Bundle args = getArguments();
TextView textView1 = view.findViewById(R.id.textview1);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss.sss", Locale.US);
String dt = df.format(Calendar.getInstance().getTime());
textView1.setText(dt);
}
public void updateView(){
Log.d("Frag", "updateView");
TextView textView2 = view.findViewById(R.id.textview2);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss.sss", Locale.US);
String dt = df.format(Calendar.getInstance().getTime());
textView2.setText(dt);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Log.d("Frag", "onAttach");
}
#Override
public void onDetach() {
super.onDetach();
Log.d("Frag", "onDetach");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/viewpager2"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tabLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TextFragment">
<TextView
android:id="#+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textview2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/textview1" />/>
</androidx.constraintlayout.widget.ConstraintLayout>
You need to notify adapter on every scroll.
pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
}
override fun onPageSelected(position: Int) {
myToast(applicationContext, "1 changes $position")
tapPosition = position
super.onPageSelected(position)
}
override fun onPageScrollStateChanged(state: Int) {
if (state.equals(0))
{
pagerAdapter.notifyItemChanged(tapPosition)
}
super.onPageScrollStateChanged(state)
}
})
onPageScrollStateChanged here you must notify adapter.

Should I use a nested fragment for tabs in a fragment?

I have a Main Activity which uses an AHBottomNavigationView for a menu at the bottom of the screen. When a different menu item is clicked, it creates a new fragment corresponding to that menu item with logic like so (condensed switch statement for the simplicity of this question):
fragmentManager.beginTransaction().replace(R.id.content_id, New TheFragmentForTheTabClicked).commit();
Where content_id is the ID of the Main Activity's ConstraintLayout.
Within the fragment for my first navigation menu item, there are two more tabs (using TabLayout), which replace the screen space with another fragment. This is done with a FragmentPagerAdapter, which is set onto a ViewPager, so tapping each tab changes the sub fragment. So at this point, there is a fragment nested in a fragment nested in a class. Here is what it generally is:
Main Activity
|
+-- Fragment 1 (selected from AHBottomNavigationView)
| |
| +-- Sub-Fragment 1 (selected by clicking the first tab in Fragment 1)
| |
| +-- Sub-Fragment 2 (selected by clicking the second tab in Fragment 1)
|
+-- Fragment 2 (selected from AHBottomNavigationView)
|
+-- Fragment 3 (selected from AHBottomNavigationView)
|
+-- Fragment 4 (selected from AHBottomNavigationView)
So my question is this:
Is the way I am doing this correct, and if not, what would a better way be?
Also, I'm finding that When I tab to Fragment 1 the first time, the swiping and tapping between the two tabs works fine, however if I tap a different bottom navigation menu item (i.e. Fragment 3) and then go back, I get the following 2 issues:
The content in either of the subfragments is not shown
Swiping between the two tabs no longer works. Instead of one motion moving to the different tab, I have to pull across the screen entirely because the indicator gets "stuck" part way between two tabs.
If there is any more information that I can provide, please let me know and I will.
Fragment1.java:
package com.mypackage.mypackage;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class Fragment1 extends Fragment {
private FragmentActivity mContext;
public Fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_1, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) getView().findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
// using getFragmentManager() will work too
Fragment1PagerAdapter adapter = new Fragment1PagerAdapter(mContext.getSupportFragmentManager(), mContext);
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) getView().findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
}
/**
* Override to set context. This context is used for getSupportFragmentManager in onCreateView
* #param activity
*/
#Override
public void onAttach(Activity activity) {
mContext=(FragmentActivity) activity;
super.onAttach(activity);
}
}
fragment_1.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabBackground="#color/fragment1TabBackground"
app:tabIndicatorColor="#color/fragment1TabIndicatorColor"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Fragment1PagerAdapter.java
package com.mypackage.mypackage;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.content.Context;
public class Fragment1PagerAdapter extends FragmentPagerAdapter {
private Context context;
public Fragment1PagerAdapter(FragmentManager fm, Context mContext){
super(fm);
context = mContext;
}
#Override
public Fragment getItem(int position){
if (position == 0){
return new SubFragment1();
}
else{
return new SubFragment2();
}
}
#Override
public int getCount() {return 2;}
#Override
public CharSequence getPageTitle(int position) {
switch(position){
case 0:
return context.getResources().getString(R.string.sub_fragment_1_page_title);
case 1:
return context.getResources().getString(R.string.sub_fragment_2_page_title);
default:
return null;
}
}
}
When nesting Fragments inside Fragment with ViewPager and swipe feature as FragmentManager which needs to be provided to Adapter recommended is to use: getChildFragmentManager() instead of getSupportFragmentManager() or getFragmentManager(). Because both are actually related to Activities instead of getChildFragmentManager(), as documentation says, is related to Fragment:
Return a private FragmentManager for placing and managing Fragments
inside of this Fragment.

Android FragmentActivity from inside Fragment

In my Android application I have created a simple Navigation Drawer which calls fragments when an item is clicked. From one of these fragments, I want to call a FragmentActivity (which will make scrollable tabs from within one of my fragments). Is this possible? Can someone please help me. A similar example to what I'm trying to achieve is in Play Music. It has a Navigation Drawer and upon selecting 'My Library' it creates a Fragment with scrollable tabs whilst still having the NavDrawer accessible from that page.
Regards,
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import cgg.gov.in.apps.eoffice.source.R;
public class TestTabsinsideFragment extends Fragment
{
View rootView;
public TestTabsinsideFragment ()
{
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
getActivity().getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Apply the layout for the fragment
rootView = inflater.inflate(R.layout.approve_leaves, container, false);
getActivity().setTitle("New tabbed layout inside Fragment :-) ");
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// show the given tab
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// hide the given tab
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// probably ignore this event
}
};
// Add 3 tabs, specifying the tab's text and TabListener
for (int i1 = 0; i1 < 3; i1++) {
getActivity().getActionBar().addTab(
getActivity().getActionBar().newTab()
.setText("Tab " + (i1 + 1))
.setTabListener(tabListener));
}
return rootView;
}
Did this answer your question ??
Include this code in your Fragment and call it from onSelectItem() of Nav-Drawer

method getfragmentmanager() is undefined

I am making a view pager to make a slide show for images. I took code from Android developers, but I was facing some issues, fragment was not recognized, I think it was because my android was 2.33. So to solve that I imported a jar file android.support.v4.jar
My issues were resolved but now I am getting this error that getfragmentmanager() is undefined
and another issue "The method invalidateOptionsMenu() is undefined for the type new ViewPager.SimpleOnPageChangeListener(){}"
Here is my code, can any one please help ??
My platform is 2.3.3 and api level is 10 and in manifest I have this
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
Code :
package com.example.profilemanagment;
import android.support.v4.app.Fragment;
import android.support.v4.app.*;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class ScreenSlideActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 5;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When changing pages, reset the action bar actions since they are dependent
// on which page is currently active. An alternative approach is to have each
// fragment expose actions itself (rather than the activity exposing actions),
// but for simplicity, the activity provides the actions in this sample.
invalidateOptionsMenu();
}
});
}
/**
* A simple pager adapter that represents 5 {#link ScreenSlidePageFragment} objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
Quoting from the docs.
When using this class (FragmentActivity) as opposed to new platform's built-in fragment and loader support, you must use the getSupportFragmentManager() and getSupportLoaderManager() methods respectively to access those features.
Since you are extending FragmentActivity use getSupportFragmentManager()
http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html
Check the docs
FragmentActivity does not have getFragmentManager()

Action Bar Tabs without using Fragments?

It is maybe quite a newbie question but anyway. Since Tabhost is depreciated I tried to switch to the action bar tabs but I have my problems using fragments. Is there a possibility to use activities within the action bar tabs anyway?
I would appreciate any help.
Thanks.
If you're set on using Activities over Fragments you could just use an intent to launch your activity from your ActionBar.TabListener
startActivity(new Intent(thisActivity(), thatActivity.class));
You should also check out this comment about using Fragments over Activities
Is there a possibility to use activities within the action bar tabs anyway?
Fortunately, no.
That does not mean you have to use fragments, though. Your TabListener can do whatever it wants to affect the change in your UI. A brute-force solution would be to call setContentView() again, to dump all your old widgets and lay down a brand-new (presumably different) set.
It's possible to use an Activity with the ActionBar. Beware this is not intended behaviour though, but that doesn't mean it doesn't work perfectly.
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
//#SuppressLint("NewApi")
public class ActionBarActivity extends Activity {
private String TAG = getClass().getName();
private Intent i = null;
private ActionBar actionBar;
private Tab one;
private Tab two;
private Tab three;
// create a tab listener that is called when the user changes tabs
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
if (tab.getTag().equals("one")){
Log.d(TAG, "tab one selected");
i = new Intent(getApplicationContext(), One.class);
determineRun();
}
if (tab.getTag().equals("two")){
Log.d(TAG, "tab two selected");
i = new Intent(getApplicationContext(), Two.class);
determineRun();
}
if (tab.getTag().equals("three")){
Log.d(TAG, "tab three selected");
i = new Intent(getApplicationContext(), Three.class);
determineRun();
}
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
// we only need to start the Activity if it's not actually already the current Activity!
void determineRun(){
if (!TAG.equals(i.getComponent().getClassName())){
startActivity(i);
}
return;
}//end method
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setSubtitle(getResources().getString("subtitle"));
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
one = actionBar.newTab();
one.setText("Tab 1").setTag("one");
two = actionBar.newTab();
two.setText("Tab 2").setTag("two");
three = actionBar.newTab();
three.setText("Tab 3").setTag("three");
one.setTabListener(tabListener);
two.setTabListener(tabListener);
three.setTabListener(tabListener);
// You will have to set the selected Tab manually
// A good idea would be to create a subclass for each Tab based on this code
// Then, just create a new Activity which extends ActionBarActivity
actionBar.addTab(one, 0, false);
actionBar.addTab(two, 1, true); // selected Tab
actionBar.addTab(three, 2, false);
}//end method
#Override
public void onResume(){
super.onResume();
Log.d(TAG, "onResume()");
Log.d(TAG, ""+i.getComponent().getClassName());
// again, here you need to select the Tab manually
if (!TAG.equals(i.getComponent().getClassName())){
actionBar.selectTab(two); // selected Tab
}
}//end method
#Override
public void onPause(){
super.onPause();
Log.d(TAG, "onPause()");
}//end method
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
}//end method
}//end class
You probably want to override the animation in your Activity so the change of tabs is seemless.
To do so, modify the onCreate() method of your Activity which extends ActionBarActivity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(0, 0);
}//end method
if my understanding is correct, you want to use action bar to swap activity instead of fragment. in this case, please continue to read.
from the official document you can see, the actionbar feature defines a set of ui, position. if you want to implement actionbar with activity, the most important thing to do is
1. to associate your tab(position) with your activity.
2. add tablistener callback(instantiate your new activity, stop the current activity) every time the tab is click
the best design is to have the tablistener implemented a seperate class, so that each of your activity could use this class.

Categories

Resources