Change fragment on click - android

I have to implement an application in which the user can click through a bottom_bar between 5 pages (although google does not recommend it in recent documents, the customer is always right).
So I created a swipe activity with automatic tool android study.
Question: how do I start the transation, after the click on the button, and change fragment??
Here is the code (at the time the activity change with the swipe)
public class Home extends ActionBarActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ImageView home, ospitalita,multimedia,territoro, prodotti;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
home = (ImageView) findViewById(R.id.ibHome);
ospitalita = (ImageView) findViewById(R.id.ibOspitalita);
multimedia = (ImageView) findViewById(R.id.ibMultimedia);
territoro = (ImageView) findViewById(R.id.ibTerritorio);
prodotti = (ImageView) findViewById(R.id.ibProdotti);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
View.OnClickListener gestore = new View.OnClickListener() {
#Override
public void onClick(View v) {
//this is the bottom bar, on click, change icon color
switch (v.getId()){
case R.id.ibHome:
changeBottomIcon("home");
mSectionsPagerAdapter.getItem(0); //do nothing
break;
case R.id.ibOspitalita:
changeBottomIcon("ospitalita");
mSectionsPagerAdapter.getItem(1);
break;
case R.id.ibMultimedia:
changeBottomIcon("multimedia");
mSectionsPagerAdapter.getItem(2);
break;
case R.id.ibTerritorio:
changeBottomIcon("territorio");
mSectionsPagerAdapter.getItem(3);
break;
case R.id.ibProdotti:
changeBottomIcon("prodotti");
mSectionsPagerAdapter.getItem(4);
break;
}
}
};
home.setOnClickListener(gestore);
ospitalita.setOnClickListener(gestore);
multimedia.setOnClickListener(gestore);
territoro.setOnClickListener(gestore);
prodotti.setOnClickListener(gestore);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
switch (position) {
// change bottom doesn't work here
case 0:
// changeBottomIcon("home");
return new fragment_home();
case 1:
//changeBottomIcon("territorio");
return new fragment_territorio();
case 2:
//changeBottomIcon("ospitalita");
return new fragment_ospitalita();
case 3:
//changeBottomIcon("multimedia");
return new fragment_multimedia();
case 4:
//changeBottomIcon("prodotti");
return new fragment_prodotti();
}
return null;
}
#Override
public int getCount() {
//num pagine
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
//Not visible, no nav bar
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.home);
case 1:
return getString(R.string.territorio);
case 2:
return getString(R.string.ospitalita);
case 3:
return getString(R.string.multimedia);
case 4:
return getString(R.string.prodotti);
}
return null;
}
}
//simple method to change icon color
public void changeBottomIcon(String tipo){
.
.
.
//lo ometto perchè inutile
}
}

You can achieve this by calling:
mViewPager.setCurrentItem(index);
(see the android dev docs for further information)

Related

Why my async task is too slow when it uses in pager adapter

I am using the following code
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
SectionsPagerAdapter mSectionsPagerAdapter= new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
My SectionsPagerAdapter class is
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
int numpages = 0;
numpages=5;
return numpages;
}
#Override
public CharSequence getPageTitle(int position) {
// Locale l = Locale.getDefault();
String chnl_name = "";
switch (language) {
case 1:
chnl_name = Constants.telugu_channels[position];
break;
case 2:
chnl_name = Constants.tamil_channels[position];
break;
case 3:
chnl_name = Constants.english_channels[position];
break;
case 4:
chnl_name = Constants.hindi_channels[position];
break;
}
return chnl_name;
}
}
and fragment class is
// enter code here
public static class DummySectionFragment extends Fragment {
GridView gridplaylst;
ProgressBar progress;
Play_list playlist;
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_grid, container,
false);
// dummyTextView.setText(Integer.toString(getArguments().getInt(
// ARG_SECTION_NUMBER)));
gridplaylst = (GridView) rootView.findViewById(R.id.gridplaylst);
progress = (ProgressBar) rootView.findViewById(R.id.progress);
if (playlist != null)
playlist.cancel(true);
if (language != 0) {
int a = getArguments().getInt(ARG_SECTION_NUMBER);
switch (language) {
case 1:
playlist = new Play_list(
Constants.telugu_playlists[getArguments().getInt(
ARG_SECTION_NUMBER) - 1]);
playlist.execute();
break;
case 2:
new Play_list(Constants.tamil_playlists[getArguments()
.getInt(ARG_SECTION_NUMBER) - 1]).execute();
break;
case 3:
new Play_list(Constants.english_playlists[getArguments()
.getInt(ARG_SECTION_NUMBER) - 1]).execute();
break;
case 4:
new Play_list(Constants.hindi_playlists[getArguments()
.getInt(ARG_SECTION_NUMBER) - 1]).execute();
break;
}
}
}
and playlist is a async task like
public class Play_list extends AsyncTask<Object, Object, Object> {
protected Object doInBackground(Object... arg0) {
}
}
Here all the functionality is working fine, but my problem is the data downloading by the async tasks is too slow.
I think the problem is creating a new task every time.
Please suggest me how can i overcome this problem.
#Prakash : There is a catch while you use ViewPager. ViewPager will start preparing view for next 2 fragments and as when your activity with ViewPager is called by System , ViewPager will creating next 2 views that you have defined in FragmentPagerAdapter.
You can use setOffscreenPageLimit(pagestoCache) to minimize this functionality.
Prakash , now you have to call asyn task only when fragment is visible to user and cancel if user moves out of current fragment. Why i am asking because if you are not cancelling the Aync task there will be many thread will be running in application space. You can also chaeck if you can use ThreadPoolExecutor in your code.
Are you aware of the fact, that Android does not run AsyncTasks in parallel? If you start many AsyncTasks in a row, they are queued and executed one after the other?
You can overcome this, by starting them with executeOnExecutor(...) instead of regular execute().

How do I tap to move to the next ViewPager page fragment?

I have a ViewPager setup that's been working fine for my app but it only lets me swipe the screen to move to the next slide. What I want is to also be able to move to the next slide by tapping the screen. Is this possible?
I've been trying to figure this out for a week but I couldn't find the right code to make it work.
Here's what I've done so far:
public class JoyfulHappyfuntime extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_joyful_happyfuntime);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return new BoopTheName();
case 1: return new Creed();
case 2: return new Waffles();
case 3: return new Smilea();
case 4: return new Smileb();
case 5: return new Smilec();
case 6: return new PancakesOne();
case 7: return new FirstJoyfulHappyfuntime();
case 8: return new Waffles();
case 9: return new Smilea();
case 10: return new Smileb();
case 11: return new Smilec();
//etc
default: return new Continue();
}
}
#Override
public int getCount() {
return 74;
}
}
}
You can try one of those :
Adding a transparent view ontop where you handle the onClick to change
the position to the next.
using a ViewPagerIndicator on top to let the user click on the section he wants
View Pager Tutorial

Send network request as FragmentPagerAdapter shows the Fragment

I am using the FragmentPagerAdapter which shows three fragments by using ViewPager. I have setOffscreenPageLimit to 3 so all the three fragments send the network request simultaneously as they are visible(I have send the network request on Fragment.onActivityCreated()). But I want network request is send only when Fragment is visible(means user is scrolled to that fragment).
Note: I am using the setOffscreenPageLimit to 3 because every time the fragment is created no new network request is created and show the catches fragment
Making network requests in oncreateview () of every fragment should do what you want to.
example :Something that ive been using .
Parent activity with fragment pager adapter.
public class HomeActivity extends SherlockFragmentActivity{
private static final String[] CONTENT = new String[] { "Fragment 1", "Fragment 2" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homexml);
Bundle extra = getIntent().getExtras();
int i = Integer.parseInt(extra.getString("id"));
FragmentPagerAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(adapter);
TitlePageIndicator indicator = (TitlePageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(pager);
switch (i)
{
case 2:
pager.setCurrentItem(0);
break;
case 3:
pager.setCurrentItem(1);
// break;
// case 4:
// pager.setCurrentItem(3);
// break;
// case 5:
// pager.setCurrentItem(4);
// break;
// case 6:
// pager.setCurrentItem(5);
// break;
// case 7:
// pager.setCurrentItem(6);
// break;
// default:
// pager.setCurrentItem(0);
// break;
}
indicator.setFooterIndicatorStyle(IndicatorStyle.Underline);
indicator.setFooterColor(Color.parseColor("#e7c450"));
}
class FragmentAdapter extends FragmentPagerAdapter {
SherlockFragment frg;
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public SherlockFragment getItem(int position) {
switch (position)
{
case 0:
frg = new fragment1();
break;
case 1:
frg = new fragment2();
break;
}
return frg;
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position];
}
// #Override public int getIconResId(int index) {
// return ICONS[index];
// }
#Override
public int getCount() {
return CONTENT.length;
}
}
Pass specify the fragments in the adapter. make network requests in onCreateView() of every fragment. that way network requests will be only made when fragment is visible.

NullPointerException with ViewPager after the app has been killed

I have 3 pages in a ViewPager: instances of Tab0, Tab1, Tab2. In the main Activity, I'm storing the instance of each tab in separte variables from the SectionsPagerAdapter's getItem() function.
I assume that ViewPager always initializes the current tab, the tab to the left of it, and the tab to the right of it.
These are my instances: Tab0 t0; Tab1 t1; Tab2 t2;
The app works fine initially. But if i press the home button (to trigger onPause()), kill the app from task killer (or assume that android itself has killed it), and open the app again, i get NullPointerExceptions in onPageSelected because t0, t1 and t2 are now null.
This is my onCreate method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
switch(pos){
case 1:
t1.lookup()
break;
case 0:
t0.doSomething();
break;
case 2:
t2.someThingElse();
break;
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
mViewPager.setCurrentItem(1,true);
}
This is my FragmentPagerAdapter (which is a nested class inside my Activity):
public class SectionsPagerAdapter extends FragmentPagerAdapter {
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 DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment;
switch(position){
case 0:
fragment = t0 = new Tab0();
break;
case 1:
fragment = t1 = new Tab1();
break;
case 2:
fragment = t2 = new Tab2();
break;
default:
fragment=null;
}
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position + 1);
if(fragment!=null)
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 1:
return getString(R.string.T1).toUpperCase(l);
case 0:
return getString(R.string.T0).toUpperCase(l);
case 2:
return getString(R.string.T2).toUpperCase(l);
}
return null;
}
}
From the Docs:
The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. Meaning when it comes back the fragments will be recreated for you but will not be the original ones(hence your loss of t* variables). I'd take a look at overriding saveState and restoreState methods to see if you can add the logic for setting up what the t* variables. If not perhaps in one of the other on* methods in the fragment.

Android scrollable Tabbar

is it somehow possible to have horizontal scrollable tabbar if there are more than e.g. 10 tabs in it?
Have anybody implemented something like this?
Mur
Ps.
It was not nice, what I did: I've deleted almost the same topic, I'd started yesterday. A big SORRY for man, who answered it already, even if it wasn't really the answer I'm looking for.
There actually is a way to implement this and it is called swipeable tabs layout. I have managed to use it in one of the apps I developed and published on Google Play. Here is the code to implement it:
SectionPagerAdapter class:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new Fragment();
switch (position) {
case 0:
return fragment = new HomeFragment();
case 1:
return fragment = new EventFragment();
case 2:
return fragment = new CoreTeamFragment();
case 3:
return fragment = new MapsFragment();
case 4:
return fragment = new FacebookFragment();
default:
break;
}
return fragment;
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
#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);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
case 4:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
Main class
public class CentruActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_centru);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// getActionBar();
}
public ActionBar getActionBar() {
return null;
}
}
Hope this helps :)

Categories

Resources