android-How to change sliding tab default position - java

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);

Related

when moving from one fragment to other the elements of the former staying on screen

so i got one main activity that has a Tablayout and a ViewPager to present diffrent fragments.
when i move between the fragments with my Tablayout everything works good, but if i use a button to open fragment, when going back to the former fragment (by pushing the cancel button) the elements of the fragment i left staying on the screen (as in the picture).
i tried to use a method viewPager.setCurrentItem(0); in the fragment to go back to the homepage from the fragment instade of ft.replace(R.id.fragment_edit_reminder, new Main_Activity_fragment()).commit(); but it didn't moved back to my home fragment (with the repalce it does go back but as i saied the elements.
this is my main:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TabLayout tableLayout = findViewById(R.id.Tablayouting);
final ViewPager viewPager = findViewById(R.id.ViewPager);
PagerAdapter pagerAdapter = new
PagerAdapter(getSupportFragmentManager(),tableLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
tableLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
this is the fragment:
public class edit_reminder_fragment extends Fragment implements View.OnClickListener {
private Button cancelButton;
public edit_reminder_fragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment edit_reminder_fragment.
*/
public static edit_reminder_fragment newInstance() {
edit_reminder_fragment fragment = new edit_reminder_fragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void onClick(View view)//TODO: make a utility method for switching fragments on the main_activity_fragment(see note).
{
switch (view.getId()) {//recognizing what button was pushed
case R.id.ButtonCancelReminder:
//region
FragmentTransaction ft = getFragmentManager().beginTransaction();
Main_Activity_fragment maf = new Main_Activity_fragment();
ft.replace(R.id.fragment_edit_reminder, maf).commit();
break;
//endregion
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_reminder_fragment, container, false);
cancelButton = view.findViewById(R.id.ButtonCancelReminder);
cancelButton.setOnClickListener(this);
return view;
}
}
my pagerAdapted class:
public class PagerAdapter extends FragmentPagerAdapter {
//https://www.youtube.com/watch?v=HHd-Fa3DCng&ab_channel=MasterCoding
private int numOfTabs;
public PagerAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Main_Activity_fragment();
case 1:
return new key_words_fragment();
case 2:
return new groups_and_points_fragment();
case 3:
return new Fragment_Past_Reminders();
case 4:
return new edit_reminder_fragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
in the picture we see the home page fragment ,on it 3 buttons (cancel, save, Add a sub reminder) that stayed from a fragment that open when clicking on the ADD NEW REMINDER button (when clicking on cancel in the second fragment it's going back to the home page):
First, try the following as an adaper:
public class PagerAdapter extends
FragmentPagerAdapter {
private final ArrayList<Fragment> mFragments = new ArrayList<>();
private final ArrayList<String> mFragmentTitle = new ArrayList<>();
public PagerAdapter(FragmentManager mManager) {
super(mManager);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitle.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitle.get(position);
}
public Fragment getFragment(int position) {
if (position < mFragments.size() && position >= 0) {
return mFragments.get(position);
}
return null;
}
}
Then in your MainActivity's onCreate, initialize the following:
mTabs = (TabLayout) findViewById(R.id.tabs);
mPager = (ViewPager) findViewById(R.id.view_pager);
mMainAdapter = new PagerAdapter( getSupportFragmentManager() );
setupContents();
Then the private method setupContents() as follows:
mMainAdapter.addFragment(new FragmentOne(), getResources().getString(R.string.tab_albums));
mMainAdapter.addFragment(new FragmentTwo(), getResources().getString(R.string.tab_songs));
mMainAdapter.addFragment(new FragmentThree(), getResources().getString(R.string.tab_playlists));
// you can add as many fragments as you wish
//just follow the previous method #mMainAdapter.addFragment
mPager.setAdapter(mMainAdapter);
mTabs.setupWithViewPager(mPager);
To get the current fragment:
public Fragment getCurrentFragment() {
return mMainAdapter.getFragment(mPager.getCurrentItem());
}
To check if the current fragment is FragmentOne:
private boolean isFragmentOne() {
return getCurrentFragment() instanceof FragmentOne;
}

Android: how to replace/delete a fragment inside section pager adapter in TabLayout

:)
I'm writing an Android app which do a lot of things, but i have an issue with java GUI code and i'm not able to go on.
What I would like to achieve is a TabLayout gui user-editable. The user could add , remove or modify section. I write all the code that let me add section. To do this i used a Section Pager Adapter as shown
class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<Fragment> mfragList;
public ArrayList<String> mfragtit;
public SectionsPagerAdapter(FragmentManager fm, ArrayList<Fragment> mFragList, ArrayList<String> mFragTit) {
super(fm);
this.mfragList=mFragList;
this.mfragtit=mFragTit;
}
#Override
public Fragment getItem(int position) {
return this.mfragList.get(position);
}
#Override
public int getCount() {
return this.mfragList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return this.mfragtit.get(position);
}
public void addFrag(Fragment frag, String tit){
this.mfragList.add(frag);
this.mfragtit.add(tit);
}
public void delFrag(int index){
this.mfragList.remove(index-1);
this.mfragtit.remove(index-1);
}
}
Well, i'm new in Android and what i've understand about this code is that this class, when called, takes two Arraylist: mfragList and mfragtit which contains the fragment of each section and its title. Then when this adapter is created it is set as the adapter of view pager, which it should be the object that contain the view.
So I get the first issue when i tried to delete one section. To do this i thought to delete both title and fragment from adapter, then notifydatasetChanged and then set again the adapter for the view pager. But it actually don't works (even if I only notifydatasetChanged while don't set adapter again).
What I do in MainActivity is something like this:
ad.delFrag(parseInt(elim_i)+1); //ad is the adapter declared as field
ad.notifyDataSetChanged();
mViewPager.setAdapter(ad);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
The issue was that it delete the right title but the wrong fragment, infact it ever delete the last fragment in mfragList
Any help gonna be appreciated.
Thank you guys.
Nico
FragmentAdapter internal have cache with loaded fragment. So that it's behaving like this. Try this adapter
public class MainActivity extends AppCompatActivity {
private TabLayout mTabLayout;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
List<Fragment> fragmentList = new ArrayList<>();
List<String> title = new ArrayList<>();
for (int i =0; i < 3; i++) {
fragmentList.add(new SampleViewPagerFragment());
title.add("Fragment #" + i);
}
final CustomPagerAdapter adapter = new CustomPagerAdapter(fragmentList, title);
mViewPager.setAdapter(adapter);
mTabLayout.setupWithViewPager(mViewPager);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
adapter.removeFragmentAtPosition(2);
}
}, 3000);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
adapter.addFragmentToAdapter("Title", new SampleViewPagerFragment());
}
}, 6000);
}
private static class CustomPagerAdapter extends PagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
private List<String> mTitle = new ArrayList<>();
CustomPagerAdapter(List<Fragment> mFragmentList, List<String> mTitle) {
this.mFragmentList = mFragmentList;
this.mTitle = mTitle;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
return mFragmentList.get(position);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
container.removeViewAt(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mTitle.get(0);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
void removeFragmentAtPosition(int position) {
mTitle.remove(position);
mFragmentList.remove(position);
notifyDataSetChanged();
}
void addFragmentToAdapter(String title, Fragment fragment) {
mTitle.add(title);
mFragmentList.add(fragment);
notifyDataSetChanged();
}
}
}

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

Java casting exception FragmentPagerAdapter

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);
}`

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