Handle back press into the Fragment - android

in my fragment i want to setVisibility for one element of my layout on back press.
for example into the fragment i want this:
if(list.getVisibility() == View.GONE){
list.setVisibility(View.VISIBLE);
text.setVisibility(View.GONE);
}
But how i can handle the back press event into the fragment? and set this visibility?
UPDATE:
In my FragmentActivity i have:
adapter = new ViewPagerAdapterEventi(getSupportFragmentManager(),Titles,Numboftabs,mE1,mE2);
// 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);
And into the Adaper:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
....
#Override
public Fragment getItem(int position) {
if (position == 0) // if the position is 0 we are returning the First tab
{
check = position;
Fragment1 tab1 = new Fragment1();
Bundle args = new Bundle();
args.putString("json", mEv1.toString());
tab1.setArguments(args);
return tab1;
} else {
Fragment2 tab2 = new Fragment2();
check = position;
Bundle args = new Bundle();
args.putString("json", mEv2.toString());
tab2.setArguments(args);
return tab2;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles.get(position);
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}

Please override method in FragmentActivity
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Fragment fragment = getSupportFragmentManager().findFragmentByTag("FRAGMENT_TAG");
fragment.setUserVisibility();
}

You have to handle this in your Activity
#Override
public void onBackPressed() {
super.onBackPressed();
MyCustomFragment fragment = (MyCustomFragment) getFragmentManager().findFragmentByTag("TAG_I_USED_WHEN_COMMITTING_FRAGMENT");
if(fragment != null) {
fragment.onBackPressed();
}
}
And create a public method in MyCustomFragment called onBackPressed() to handle everything that should happen when the back button is pressed.
note: Don't forget that your FragmentManager can also handle the onBackPressed event and remove your fragment from the back stack for example. This depends on how you've added the fragment

Related

ImageButtons Remains unchanged when returned to an old view Pager fragment

I have a HomeActivity where I have used ViewPager. There are 2 fragments home1F and home2F that come when swipe right. The HomeActivity has a top bar (used by Linerlayout) where there are 2 imagebuttons. When home1F is in the screen one button is shown(other is invisible) and when home2F is in the screen the other button is shown while the first one becomes invisible.
But when I run the app I find at first the second button is visible instead of the first one (when there is home1F). When i swipe to home2F nothing happens. When I swipe left to come back to home1F still nothing happens.
Here is the code:
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0:
//imagebutton-1 visible
//imagebutton-2 invisible
return Home1F.newInstance("FirstFragment, Instance 1");
case 1:
//imagebutton-1 invisible
//imagebutton-2 visible
return Home2F.newInstance("SecondFragment, Instance 1");
default:
//imagebutton-1 visible
//imagebutton-2 invisible
return Home1F.newInstance("FirstFragment, Instance 1");
}}
#Override
public int getCount() {
return 2;
}
}
Try this
Show the imageButton1 and hide the imageButton2 in onCreate of your Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
imag1.setVisibility(View.VISIBLE);
imag2.setVisibility(View.GONE);
So when your app launch it will show the first imageButton and hide the second imageButton
Now when you switch between tabs
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(position==0){
imag1.setVisibility(View.VISIBLE);
imag2.setVisibility(View.GONE);
}
else if(position==1){
imag1.setVisibility(View.GONE);
imag2.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if you want to switch out the actual fragments that are being displayed, you need to avoid FragmentPagerAdapter and use FragmentStatePagerAdapter.
using getItemPosition() we can update the fragments. In below example have updated fragment titles :
ViewPager pager = /* get my ViewPager */;
// assume this actually has stuff in it
final ArrayList<String> titles = new ArrayList<String>();
FragmentManager fm = getSupportFragmentManager();
pager.setAdapter(new FragmentStatePagerAdapter(fm) {
public int getCount() {
return titles.size();
}
public Fragment getItem(int position) {
MyFragment fragment = new MyFragment();
fragment.setTitle(titles.get(position));
return fragment;
}
public int getItemPosition(Object item) {
MyFragment fragment = (MyFragment)item;
String title = fragment.getTitle();
int position = titles.indexOf(title);
if (position >= 0) {
return position;
} else {
return POSITION_NONE;
}
}
});

How to update TabLayout when returning from an activity

My app I am working on has 3 tabs in TabLayout. Each is comprised of a listview. Additionally I am using a FragmentStatePageAdapter and a custom adapter. When you click on an item in the ListView it launches an activity. After you have completed a task in the activity it updates some global array data. Next the user could hit the back button on their phone to return. This is where the issue resides.
Now Tab1 never changes, I later wish to implement that returning sets it to Tab1. That's a later worry. The problem is that the middle tab does not reload. I understand the reason is because the middle tab is already created so visually the swipe effect looks accurate. Tab3 will update if coming from Tab1 because it was not loaded yet.
I have tried various listeners, working with onResume in the tablayout Fragment. I do not have notifydatasetchanged anywhere in my code and haven't been able to implement that. I presume I have somehow implemented something wrong and overpassed the correct solution being I have tried so many things.
Here is some code to help understand how I have everything setup.
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(0);
//more
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setScrollPosition(0, 0f, 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_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);
}
SectionsPagerAdapter
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
protected Context mContext;
public SectionsPagerAdapter( FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
int number = position;
switch (number) {
case 0: // Fragment # 0 - This will show FirstFragment
return TabFragment1.newInstance();
case 1: // Fragment # 0 - This will show FirstFragment different title
return TabFragment2.newInstance();
case 2: // Fragment # 1 - This will show SecondFragment
return TabFragment3.newInstance();
default:
return null;
}
// return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "All";
case 1:
return "Unfinished";
case 2:
return "Completed";
}
return null;
}}
MyAdapter
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
protected Context mContext;
public SectionsPagerAdapter( FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
int number = position;
switch (number) {
case 0: // Fragment # 0 - This will show FirstFragment
return TabFragment1.newInstance();
case 1: // Fragment # 0 - This will show FirstFragment different title
return TabFragment2.newInstance();
case 2: // Fragment # 1 - This will show SecondFragment
return TabFragment3.newInstance();
default:
return null;
}
// return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "All";
case 1:
return "Unfinished";
case 2:
return "Completed";
}
return null;
}}
Fragment1 (all three fragments are the exact same)
public class TabFragment1 extends android.support.v4.app.Fragment {
public ArrayList<String> mylist1 = new ArrayList<>();
// newInstance constructor for creating fragment with arguments
public static TabFragment1 newInstance() {
TabFragment1 fragmentFirst = new TabFragment1();
Bundle args = new Bundle();
//pass a list or something?
fragmentFirst.setArguments(args);
return fragmentFirst;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mylist1.clear();
for (int i = 0; i < arrayInt.length; i++) {
mylist1.add(array[i]);
}
final ListView listView = (ListView) rootView.findViewById(R.id.text_label);
MyAdapter adapter = new MyAdapter(getContext(), mylist1);
listView.setAdapter(adapter);
//Click on Item
//selecting items
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//goes to new activity passing the item name
Intent intent = new Intent(view.getContext(), MapsActivity.class);
Bundle b = new Bundle();
//get text for current item
//String textGet = listView.getItemAtPosition(position).toString();
String textGet = mylist1.get(position);
//put text into a bundle and add to intent
intent.putExtra("text", textGet);
//get position to carry integer
intent.putExtra("position", position);
intent.putExtras(b);
//begin other activity
startActivity(intent);
}
});
return rootView;
}
Here is an older attempt at notifying data set changed but no luck. I put this in the fragment itself.
public void onResume(){
super.onResume();
Log.e("Frag2", "Refresh Test");
// a check so it doesnt run first time starting app and crashing
if (g != 0) {
updateData();
}
g = 1;
}
private void updateData(){
Log.e("Frag2", "Refresh Test");
this.mylist2.clear();
for (int i = 0; i < arrayInt.length; i++) {
if (arrayInt[i] == 1) {
this.mylist2.add(array[i]);
}
}
adapter = new MyAdapter(getContext(), this.mylist2);
adapter.notifyDataSetChanged();
}

trigger Button onClick on ViewPager

I am setting up ViewPager on my onCreate() but when I try to set click listener one of the layout tab button, it does not respond. Here is how my onCreate() is set up.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.join_login);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new JoinLoginAdapter(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 the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
// Set up the login form.
View inflatedView = getLayoutInflater().inflate(R.layout.login_tab, null);
mEmailView = (AutoCompleteTextView) inflatedView.findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) inflatedView.findViewById(R.id.login_password);
//mPasswordView = (EditText) findViewById(R.id.login_password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login_password || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) inflatedView.findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
My JoinLoginAdapter extends FragmentStatePagerAdapter. I have three layouts, one is the ContentView whereas the other two are the two tabs for my ViewPager. The problem is mPasswordView and other buttons currently in the two tabs do not respond on click. I also have the adapter below for my ViewPager.
public class JoinLoginAdapter 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 JoinLoginAdapter(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
{
LoginFragment logintab = new LoginFragment();
return logintab;
}
else // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
JoinFragment jointab = new JoinFragment();
return jointab;
}
}
// 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;
}
}
I have been thinking the ViewPager is interfering with the clicks but I cannot seem to find how to solve this. What exactly am I doing wrong?
The problem is mPasswordView and other buttons currently in the two
tabs do not respond on click. I have been thinking the ViewPager is
interfering with the clicks but I cannot seem to find how to solve
this. What exactly am I doing wrong?
you are using a inflater, to get a reference a reference to view handled by the fragments in your ViewPager. You are doing the wrong assumption that the inflater is returning you the same view's reference that the Fragments handled by the ViewPager are inflating. What is returning the inflater in your Activity's onCreate is different from what you are seeing at screen. You should let the Fragments handle their OnClicKListener

SlidingTabLayout and Actionbar title

I'm using a SlidingTabLayout (from the Google sources) in my app to navigate between different fragments.
I can swipe between contents just fine, but the problem I'm facing is the title of the Action bar that is acting weird.
Suppose that I have two tabs with two titles ('First Title' and 'Second Title') :
| Action bar |
| First Title | Second Title |
When I first enter the Fragment containing the SlidingTabLayout, the title of the Actionbar is like this :
| Firs... |
| First Title | Second Title |
When I swipe (to the second tab for example), the title of the actionbar becomes :
| Second Title |
| First Title | Second Title |
And stays like this. It seems that the Actionbar takes the title of the last Fragment loaded when I swipe at least once.
What I want is this :
I want to show a 'Main Title' in the Actionbar that never changes no matter what the title in the SlidingTabLayout is.
Here are some portions of my code:
** Fragment containing the SlidingTabLayout:
private String mainTitle;
....
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
// The mainTitle is given to this fragment by another fragment
Bundle args = getArguments();
if (args != null) {
mainTitle = args.getString("TITLE");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
mSlidingLayout = (SlidingTabLayout) rootView.findViewById(R.id.sliding_layout);
List<Fragment> listFragments = new ArrayList<>();
List<String> listTitles = new ArrayList<>();
for (int i = 0; i < mSize; i++) {
Bundle bundle = new Bundle();
....
listFragments.add(Fragment.instanciate(getActivity(), CustomFragment.class.getName(), bundle));
listTitles.add("...");
}
mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), listFragments, listTitles));
mSlidingLayout.setDistributedEvenly(true);
mSlidingLayout.setViewPager(mViewPager);
return rootView;
}
#Override
public void onResume() {
super.onResume();
// I TRY TO SET THE TITLE HERE !!
getActivity().getSupportActionBar().setTitle(mainTitle);
}
** Adapter:
class PagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragments;
List<String> titles;
...
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
// maybe the problem is in this method.
// this method is supposed to provide the titles for the tab
// but maybe it's also changing the actionbar title
return titles.get(position);
}
I'm setting the title of the ActionBar in the onResume method every time I enter a Fragment.
Thanks !
EDIT 1 :
I tried using the new SlidingTabLayout which I've got from the Google I/O, and the result is still the same !
It seems that the Title in the ActionBar is a hint at first, and then it changes to the last loaded fragment when I swipe to another fragment.
It's like it's loading fragment, and each time a fragment is loaded, the title in the ActionBar is overridden with the title of that fragment.
EDIT 2 :
I changed my code to post the latest version of it (I'm using now a SlidingTabLayout) and to show how I get my mainTitle.
you can use below code it works fine for me
public class MatchesActivity extends AppCompatActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
FloatingActionButton skipButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matches);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
skipButton = (FloatingActionButton) findViewById(R.id.skip_next);
skipButton.setVisibility(View.GONE);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(1);
mViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
});
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
actionBar.addTab(
actionBar.newTab().setText("MATCHES")
.setTabListener(this));
actionBar.addTab(
actionBar.newTab().setText("PINS")
.setTabListener(this));
actionBar.addTab(
actionBar.newTab().setText("CHATS")
.setTabListener(this));
}
#Override
public void onBackPressed() {
startActivity(new Intent(MatchesActivity.this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK & Intent.FLAG_ACTIVITY_CLEAR_TOP));
MatchesActivity.this.finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MatchesFragment();
case 1:
return new PinsFragment();
case 2:
return new ConversationFragment();
default:
return new MatchesFragment();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
}
I am posting here a code of mine.It worked for me.Make required changes in it and try it.I used PagerSlidingTabStrip library in it.
public class DealFragment 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
View view= inflater.inflate(R.layout.fragment_deal, container, false);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getChildFragmentManager()));
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip)view.findViewById(R.id.tabs);
tabsStrip.setBackgroundColor(Color.parseColor("#333333"));
// Attach the view pager to the tab strip
tabsStrip.setViewPager(viewPager);
return view;
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
private final String tabTitles[] = new String[] { "Today's Deals", "Deals Close By" };
public SampleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
if(position==0)
{
return new TodaysDeal();
}
else
{
return new DealsCloseBy();
}
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
}
hope it might help you.
The actionBar title doesn't change because onResume() is not called the time you swipe back.
It's because ViewPager doesn't call fragment's onResume the second time. Even though in reality the fragment is resumed.
What you can do is to move the setting of your actionbar title in your parent fragment (that contains pagertabstrip) to onCreateView instead.
For your reference:
** Fragment containing the PagerTabStrip:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
List<Fragment> listFragments = new ArrayList<>();
List<String> listTitles = new ArrayList<>();
...
// HERE's what you want
final ActionBar actionBar = getActivity().getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.main_title);
}
mViewPager.setAdapter(new PagerAdapter(getChildFragmentManager(), listFragments));
return rootView;
}
Found it !
It was really dumb of me (it explains why others didn't have this problem)
I was setting the title also in each of the Fragments (even those contained in the Tabs), so when I swiped, the onResume on those Fragments was called and it changed the title in the ActionBar...
Thank you all for the help, I appreciate it !

ListView with Fragment within ViewPager

Current I have a ViewPager which have 3 different tabs(Peer, Sync and Share).
In the Peer fragment, it contain a ListView with clickable items. OnItemClick I wish to open a new fragment which will display the detail of the selected item,
But I am not sure how to properly implement this functionality...
Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.file_sharing_activity);
// Tabs stuff ...
this.tabsAdapter = new TabsPagerAdapter(this.getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(this.tabsAdapter);
// Create tabs bar
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create tab fragments
this.peerListFragment = new PeerListFragment();
this.syncFragment = new SyncFragment();
this.shareFragment = new ShareFragment();
// Create tabs
actionBar.addTab(actionBar.newTab().setText("Peers").setTabListener(this.peerListFragment));
actionBar.addTab(actionBar.newTab().setText("Sync").setTabListener(this.syncFragment));
actionBar.addTab(actionBar.newTab().setText("Share").setTabListener(this.shareFragment));
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
});
try {
ProgramController.getInstance().initializeProgram(this);
} catch (Exception e) {}
}
TabPagerAdapter:
private class TabsPagerAdapter extends FragmentPagerAdapter{
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return peerListFragment;
case 1:
return syncFragment;
case 2:
return shareFragment;
default:
return null;
}
}
#Override
public int getCount() {
return NB_TABS;
}
}
PeerListFragment
public class PeerListFragment extends Fragment implements ActionBar.TabListener{
ListView peerListView;
public PeerListFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_peer_list, container, false);
peerListView = (ListView) view.findViewById(R.id.list_peer);
PeerListAdapter adapter = new PeerListAdapter(getActivity());
peerListView.setAdapter(adapter);
peerListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Display detail fragment here
}
});
return view;
}
In general, you would have a method on your Activity that would be called from onItemClick() to display the detail view, i,e, showDetail(itemId). The Activity would actually handle the transition to the detail view.
Now, since your ViewPager is in an Activity and not a Fragment, you have two choices:
Have a DetailActivity that is started with an Intent from your current Activity. (Easiest option, but less flexible for tablets)
Rewrite your Activity to put your view with the ViewPager in a Fragment. Then the Activity would replace the current fragment that has the ViewPager with the detail fragment. (Harder option, but you can display side-by-side in a tablet).
Right now, your ViewPager is in your activity layout. In order to make the fragments work, your activity layout would just have one or two child layouts which function as fragment containers, then the ViewPager would go into a fragment layout.

Categories

Resources