Java casting exception FragmentPagerAdapter - java

I want to make a custom fragmentPagerAdapter. My application crashes and i've got cast exception. This is my code:
public class HomePagerAdapter extends FragmentPagerAdapter {
private static int[] ICONS = new int[] {
R.drawable.tab1drawable,
R.drawable.tab2drawable
};
public HomePagerAdapter(FragmentManager fm) {
super(fm);
}
// ...
#Override
public CharSequence getPageTitle(int position) {
return null;
}
#Override
public int getCount() {
return ICONS.length;
}
public int getDrawableId(int position) {
return ICONS[position];
}
#Override
public Fragment getItem(int position) {
return null;
}
}
And this is the exception :
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.androidsources.welcomescreen/com.androidsources.welcomescreen.MainActivity}:
java.lang.ClassCastException:
com.androidsources.welcomescreen.ViewPagerAdapter cannot be cast to
com.androidsources.welcomescreen.HomePagerAdapter
This is the line where crash occurs : tabs.setViewPager(pager); and this is the onCreate Method from MainActivity.cs
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// 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);
}`

Related

Java Android remove name of Application

I have a fragment and an activity. I want to display name of tags(fragments) but I don't want to show name of application in actionBar.
This is my activity: when I remove an ActionBarActivity I can not use a FragmentManager
public class ObjectListActivity extends ActionBarActivity implements android.support.v7.app.ActionBar.TabListener {
private ViewPager viewPager;
private android.support.v7.app.ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_object_list2);
// View pager for showing many fragments over a single activity
viewPager = (ViewPager) findViewById(R.id.pager);
// Getting fragment manager to control fragments
FragmentManager fragmnetManager = getSupportFragmentManager();
// Setting adapter over view pager
viewPager.setAdapter(new MyAdapter(fragmnetManager));
// Implementing view pager pagechangelistener to navigate between tabs
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
// Setting navigation of tabs to actionbar
actionBar.setSelectedNavigationItem(pos);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
// Getting actionbar
actionBar = getSupportActionBar();
// Setting navigation mode to actionbar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Now adding a new tab to action bar and setting title, icon and
// implementing listener
android.support.v7.app.ActionBar.Tab tab1 = actionBar.newTab();
tab1.setText("Wszytskie");
// tab1.setIcon(R.drawable.ic_launcher);
tab1.setTabListener(this);
android.support.v7.app.ActionBar.Tab tab2 = actionBar.newTab();
tab2.setText("Grupy");
tab2.setTabListener(this);
// Now finally adding all tabs to actionbar
actionBar.addTab(tab1);
actionBar.addTab(tab2);
}
#Override
public void onTabReselected(android.support.v7.app.ActionBar.Tab arg0,
FragmentTransaction arg1) {
}
#Override
public void onTabSelected(android.support.v7.app.ActionBar.Tab tab,
FragmentTransaction arg1) {
// Setting current position of tab to view pager
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.support.v7.app.ActionBar.Tab arg0,
FragmentTransaction arg1) {
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
// Getting fragments according to selected position
Fragment fragment = null;
if (i == 0) {
fragment = new FragmentAllObjectActivity();
}
if (i == 1) {
fragment = new FragmentGroupObjectsActivity();
}
// and finally returning fragments
return fragment;
}
#Override
public int getCount() {
// Returning no. of counts of fragments
return 2;
}
}
Inside onTabSelected add the line:
#Override
public void onTabSelected(android.support.v7.app.ActionBar.Tab tab,
FragmentTransaction arg1) {
// Setting current position of tab to view pager
viewPager.setCurrentItem(tab.getPosition());
setTitle(getText(tab.getPosition()));
}
You have to implement a getText() method which return the right text based on the current fragment like:
public String getText(android.support.v7.app.ActionBar.Tab tab){
// if tab == tabType 1 return "Title 1"
// else return "Title 2"
}
Use bellow code in your onCreate method
setTitle("");//it will remove your app name

How to stop tab change from running fragment onCreateView in Andriod

I have three tabs using the implementation below and they perform very well. When tab is changed the proper fragment is load and so on. The problem is that, when i get to the last tab and comeback to the first fragment, its like its oncreateview method is always triggered again running the other codes it in causing duplicates. Any help will be greatly appreciated.
//Activity on the tab is based
public class Dashboard extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private int[] tabIcon = {R.drawable.ic_home, R.drawable.ic_message, R.drawable.ic_person};
android.support.v7.widget.Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
//Toolbar
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//ViewPager
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
//Tablayout
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(tabIcon[0]);
tabLayout.getTabAt(1).setIcon(tabIcon[1]);
tabLayout.getTabAt(2).setIcon(tabIcon[2]);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch(tab.getPosition()) {
case 0:
viewPager.setCurrentItem(0);
toolbar.setTitle("Home");
break;
case 1:
viewPager.setCurrentItem(1);
toolbar.setTitle("Messages");
break;
case 2:
viewPager.setCurrentItem(2);
toolbar.setTitle("Profile");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager){
myViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
myViewPagerAdapter.addFragments(new CategoryFragment(), "Categories");
myViewPagerAdapter.addFragments(new MessagesFragment(), "Messages");
myViewPagerAdapter.addFragments(new ProfileFragment(), "Profile");
viewPager.setAdapter(myViewPagerAdapter);
}
//View Pager Adapter
public class MyViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragments(Fragment fragments, String titles){
this.fragments.add(fragments);
this.tabTitles.add(titles);
}
public MyViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
//return tabTitles.get(position);
return null;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
//Main first fragment code
public class CategoryFragment extends Fragment {
private DBHandler dbHandler;
private ListView listView;
private ListAdapter adapter;
ArrayList<Categories> categoriesList = new ArrayList<Categories>();
public CategoryFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
//Setting up the basic categories
dbHandler = new DBHandler(view.getContext());
//Get Categories from database
final Cursor cursor = dbHandler.getCategories(0);
if (cursor != null) {
if(cursor.moveToFirst()){
do{
Categories categories = new Categories();
categories.set_id(cursor.getInt(0));
categories.set_categoryname(cursor.getString(2));
categories.set_categoriescaption(cursor.getString(3));
categoriesList.add(categories);
}while (cursor.moveToNext());
}
cursor.close();
}
listView = (ListView) view.findViewById(R.id.categories);
adapter = new CategoryAdapter(view.getContext(), R.layout.cursor_row, categoriesList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Integer cid = (int) (long) adapter.getItemId(position);
TextView categoryname = (TextView) view.findViewById(R.id.cursor);
String cname = categoryname.getText().toString();
Intent i = new Intent(view.getContext(), CategoryList.class);
i.putExtra("categoryname", cname);
i.putExtra("categoryid", cid);
startActivity(i);
}
}
);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
So when i swipe back here from the last tab. OncreateView runs again. How can i handle that and prevent duplicates. Thank you
By defaults ViewPager retains only 1 page in the view hierarchy in an idle state.So when you swipe to third tab the viepager destroys the first tab in order to retain the second one.
To solve this issue add this line
viewPager.setOffscreenPageLimit(3);
after you set your adapter.
Check here the documentation for more

Detecting what sliding tab user is on

This is one of my first apps. I want to know how I can detect what sliding tab the user is currently on. I know it in ViewPagerAdapter but I can't do anything because it's a fragment. How can I access this information?
MainActivity.java
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"Factorial", "Permutation", "Random"};
int Numboftabs = 3;
FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.fab_pressed);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.show(false);
//Animation FAB
Animation animation = AnimationUtils.loadAnimation(this, R.anim.simple_grow);
fab.startAnimation(animation);
}
#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) {
Toast.makeText(this, "Text", Toast.LENGTH_SHORT).show();
Animation animation = AnimationUtils.loadAnimation(this, R.anim.simple_grow);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.startAnimation(animation);
return true;
}
return super.onOptionsItemSelected(item);
}
}
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
{
FactorialTab factorialTab = new FactorialTab();
return factorialTab;
} else if(position == 1) // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
PermutationTab permutationTab = new PermutationTab();
return permutationTab;
}
else {
RandomTab randomTab = new RandomTab();
return randomTab;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
RandomTab.java (one of the sliding tabs)
public class RandomTab extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_random, container, false);
return v;
}
}
Set an OnPageChangeListener to your ViewPager
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == WHATEVER) {
//do what you want
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

android-How to change sliding tab default position

this is my code for making sliding tab .It makes tabs perfectly .
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstactivity);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),FistActiivty.this));
// Give the SlidingTabLayout the ViewPager
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
// Center the tabs in the layout
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setViewPager(viewPager);
slidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return Color.RED;
//or return getResources().getColor(R.color.red);
}
});
}
class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 4;
private String tabTitles[] = new String[] { "Tab1", "Tab2", "Tab3" , "Tab4"};
private Context context;
public SampleFragmentPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
if (position==0){
fragment=new Fragment_A();
}
if (position==1){
fragment=new Fragment_B();
}
if (position==2){
fragment=new Fragment_C();
}
if (position==3){
fragment=new Fragment_C();
}
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
The question is ,How can I change the default selected tab when activity runs ?
How can I change the default tab position to third when activity opens ?
Use this, it will select a particular tab on load
mViewPager.setCurrentItem(position);

Replace a fragment above another fragment when dialog is clicked (viewpager)

I am trying to open a fragment, when a dialog is clicked inside another fragment. I am using ActionBarSherlock with Tab. My fragment is attached in the view pager. I have almost done the job. But I can't replace a new fragment inside a view pager. I got an error. I read the thread here. The solution isn't clear.
Error:
10-18 21:34:40.379: E/AndroidRuntime(19618): FATAL EXCEPTION: main
10-18 21:34:40.379: E/AndroidRuntime(19618):
java.lang.IllegalArgumentException: No view found for id 0x7f040032
(com.example.actionbartestwithsherlock:id/pager) for fragment
AllContactsFragment{41fd4ba0 #0 id=0x7f040032} 10-18 21:34:40.379:
E/AndroidRuntime(19618): at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
I have three fragment associates with pager named FragmentTab1,FragmentTab2 & FragmentTab3.
My MainActivity & FragmentAdapter looks like below:
public class MainActivity extends SherlockFragmentActivity {
ActionBar.Tab Tab1, Tab2, Tab3, Tab4;
private Context context = this;
// view pager
// Declare Variables
ActionBar actionBar;
ViewPager mPager;
Tab tab;
FragmentAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set application in portrait mode
ActivityHelper.initialize(this);
actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Locate ViewPager in activity_main.xml
mPager = (ViewPager) findViewById(R.id.pager);
// add an adapter to pager
mPager.setAdapter(new FragmentAdapter(getSupportFragmentManager(),
mPager, actionBar));
addActionBarTabs();
}
private void addActionBarTabs() {
String[] tabs = { "Tab 1", "Tab 2", "Tab 3" };
for (String tabTitle : tabs) {
ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
.setTabListener(tabListener);
actionBar.addTab(tab);
}
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
private ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
class FragmentAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener {
private ViewPager mViewPager;
final int TOTAL_PAGES = 3;
public FragmentAdapter(FragmentManager fm, ViewPager pager,
ActionBar actionBar) {
super(fm);
this.mViewPager = pager;
this.mViewPager.setOnPageChangeListener(this);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentTab1.newInstance();
case 1:
return FragmentTab2.newInstance();
case 2:
return FragmentTab3.newInstance();
default:
throw new IllegalArgumentException(
"The item position should be less or equal to:"
+ TOTAL_PAGES);
}
}
#Override
public int getCount() {
return TOTAL_PAGES;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
}
}
Now, Inside my first tab FragmentTab1, I open a customized dialog when a button clicks. I want to replace new fragment AllContactsFragment in FragmentTab1 when the dialog options are selected.
FragmentTab1 fragment class:
public class FragmentTab1 extends SherlockFragment implements OnClickListener {
Button btnTest;
ViewPager pager;
LinearLayout layoutBlockNumbers;
LinearLayout layoutContact, layoutCallLog, layoutSMSLog, layoutManually;
Context context;
CustomizedDialog dialog;
private static final int CONTACT_PICKER_RESULT = 1001;
private static final String DEBUG_TAG = "Contact List";
private static final double RESULT_OK = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container,
false);
layoutBlockNumbers = (LinearLayout) rootView
.findViewById(R.id.layoutAddBlockNumbers);
layoutBlockNumbers.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
if (v == layoutCallLog) {
dialog.dismiss();
// want to replace new fragment at position 0 in pager
// problem is here ??? how to open new fragmnet
Fragment allContactsFragment = AllContactsFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.pager, allContactsFragment).commit();
}
if (v == layoutBlockNumbers) {
// open a dialog
showDialog();
} else if (v == layoutContact) {
openContactList();
dialog.dismiss();
} else if (v == layoutSMSLog) {
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
// open a dialog
private void showDialog() {
dialog = new CustomizedDialog(getActivity());
dialog.setContentView(R.layout.dialog_add_number_type);
dialog.setTitle("Add Black List Number");
//initialize all linear layouts in dialog
layoutCallLog = (LinearLayout) dialog.findViewById(R.id.layoutCallLog);
layoutContact = (LinearLayout) dialog.findViewById(R.id.layoutContact);
layoutSMSLog = (LinearLayout) dialog.findViewById(R.id.layoutSMSLog);
layoutManually = (LinearLayout) dialog
.findViewById(R.id.layoutManually);
// add listener to several linear layout
layoutContact.setOnClickListener(this);
layoutCallLog.setOnClickListener(this);
layoutSMSLog.setOnClickListener(this);
layoutManually.setOnClickListener(this);
dialog.show();
}
public static Fragment newInstance() {
Fragment f = new FragmentTab1();
return f;
}
}
activity_main.xml looks like below :
<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="wrap_content" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
Can anybody can help me to solve this issue? Sorry for the massive code.
I'm not sure you can do things the way you want to. A ViewPager is not set up the same way a normal container/fragment set up would be. In a ViewPager you're not using fragment transactions to add fragments but rather an adapter that loads instances of fragments from a backing list.
Replacing the fragment would then work as follows:
(1) Create an instance of the fragment you want to add
(2) Add that fragment to the list that is backing your PagerAdapter
(3) Display the new fragment
(4) Remove the old one
The problem with implementing this in your current project is the set up of your adapter. Currently you are using a switch statment that can only return a fixed number of fragments. Your adapter should be set up something like this.
class MyPageAdapter extends FragmentPagerAdapter{
private List<Fragment> fragments
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
Then you can just add a method to your adapter class to add or remove new fragments. If you know the index of the fragment you want to replace accomplishing this should be pretty easy. All you have to do is create a new instance of the contacts fragment, add it to your array or list. This Post explains how a ViewPager handles the adding/removing of new content and how to ensure your new fragment is displayed.
After I read this post I solved the answer.
I just add an ID android:id="#+id/fragmentTabLayout1 to top layout of my fragmenttab1.xml . Then call
new fragment as usual:
Fragment allContactsFragment = AllContactsFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
// use this id to replace new fragment
transaction.replace(R.id.fragmentTabLayout1, allContactsFragment).commit();

Categories