I am doing swiping application in android. But I got one problem that getItem() method
is calling twice initially. I tried to solve this but I didn’t get solution. please help me
to find out solution. below snippets my code:-
public class DisplayEMIBOFQuestionActivity extends FragmentActivity {
private ViewPager pager;
private int savePosition;
private Context context;
private String fragTag1;
private String fragTag2;
/*
* (non-Javadoc)
*
* #see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.common_emi_bof_display_question);
context = getLayoutInflater().getContext();
if(Helper.isTablet)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// Initialise the pager
pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
/**
* on swiping the viewpager make respective tab selected
* */
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageSelected(int position) {}
public void onPageScrolled(int position, float arg1, int arg2) {}
public void onPageScrollStateChanged(int arg0) {
}
});
getPager().setPageTransformer(true, new SwipeAnimation());
}
public ViewPager getPager() {
return pager;
}
public void setPager(ViewPager pager) {
this.pager = pager;
}
public String getFragTag1() {
return fragTag1;
}
public void setFragTag1(String fragTag1) {
this.fragTag1 = fragTag1;
}
public String getFragTag2() {
return fragTag2;
}
public void setFragTag2(String fragTag2) {
this.fragTag2 = fragTag2;
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int pos) {
System.out.println("************** "+pos);
Helper.currentQuestion = pos;
if(Helper.randomQuestionList.get(pos).getSubQuestionType().equals(QuestionType.BOF.toString()))
return new DisplayBOFQuestionFragment();
else
return new DisplayEMIQuestionFragment();
}
#Override
public int getCount() {
return Helper.NUMBEROFQUESTIONS;
}
#Override
public CharSequence getPageTitle(int position) {
return super.getPageTitle(position);
}
}
public void setPagerPosition(int pos){
pager.setCurrentItem(pos);
}
}
It gets one fragment and two adjacent ones (here you just have one), so initially will get Tab1 and Tab2 to get ready when you swipe to Tab2, at Tab2 selected will also call getItem for Tab3 to prepare for swipe.
Related
I have this "frame" app with toolbar and viewPager.
BaseActivity:
public abstract class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
}
protected abstract int getLayoutResource();
}
ToolbarActivity:
protected static Toolbar toolbar;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = findViewById(R.id.flToolbarContentContainer);
if (contentView instanceof ViewGroup) {
((ViewGroup) contentView)
.addView(LayoutInflater.from(this)
.inflate(getToolbarLayoutResource()
, (ViewGroup) contentView, false));
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
protected int getLayoutResource() {
return R.layout.activity_toolbar;
}
protected abstract int getToolbarLayoutResource();
public void showToolbar() {
toolbar.setVisibility(View.VISIBLE);
}
public void hideToolbar() {
toolbar.setVisibility(View.GONE);
}
public static void setTitle(String title){
toolbar.setTitle(title);
}
}
MainActivity:
public class MainActivity extends ToolbarActivity {
#Override
protected int getToolbarLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabFragment homeFragment = new TabFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.llMainActivityContainer, homeFragment)
.commit();
}
And The. TabFragment:
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
private String[] titles = new String[3];
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
titles[0] = "Összes";
titles[1] = "Saját";
titles[2] = "Közelben";
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.view_pager,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
ToolbarActivity.setTitle(""+titles[position]);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragment();
case 1 : return new SecondFragment();
case 2 : return new ThirdFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
My problem is if I open a new activity from the viewPager and finish it,
when I return to the viewPager activity the onPageSelected listener runs but not changing my toolbar title.
Can you help me how can I solve this?
Thank you!
try
getActivity.setTitle(""+titles[position]);
i found an example to use fragments without using tabBar
but now i founded that a fragment OnCreatView called on previos fragment and with this i haven't any control to lifecycle of fragment
this is my code
public class AddTextActivity AppCompatActivity {
private PagerAdapter mPagerAdapter;
public static FragmentManager frmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cordinate);
frmanager=getSupportFragmentManager();
initialisePaging();
}
private void initialisePaging() {
List<Fragment> fragments = new Vector<>();
fragments.add(Fragment.instantiate(this,Frags.Addtext1.class.getName()));
fragments.add(Fragment.instantiate(this,Frags.Addtext2.class.getName()));
fragments.add(Fragment.instantiate(this,Frags.Addtext3.class.getName()));
this.mPagerAdapter = new PagerAdapter1(frmanager, fragments);
ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);
pager.setAdapter(this.mPagerAdapter);
}
and this is the pagerAdapter1
public class PagerAdapter1 extends FragmentPagerAdapter {
private List<Fragment> fragments;
/**
* #param fm
* #param fragments
*/
public PagerAdapter1(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
/* (non-Javadoc)
* #see android.support.v4.app.FragmentPagerAdapter#getItem(int)
*/
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
/* (non-Javadoc)
* #see android.support.v4.view.PagerAdapter#getCount()
*/
#Override
public int getCount() {
return this.fragments.size();
}
}
so now how can i prevent from calling onCreatView of next fragment ??
For determine which page is selected:
mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// TODO insert your code here
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
I have two images. I used ViewPager to display them individually. I want to know which ones is displaying in the screen. Could you help me to solve it? For example, when I scroll the screen, the first image will display and Toast a message such as "This is first image", do same thing for second image. Thanks in advance. This is my code
public class ViewPagerExample extends FragmentActivity{
private MyAdapter mAdapter;
private ViewPager mPager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
{
return new ImageFragment(R.drawable.image1);
}
case 1:
{
return new ImageFragment(R.drawable.image2);
}
default:
return null;
}
}
}
}
and the ImageFragment class
public class ImageFragment extends Fragment {
private final int imageResourceId;
public ImageFragment(int imageResourceId) {
this.imageResourceId = imageResourceId;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_layout, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
imageView.setImageResource(imageResourceId);
return view;
}
}
try something like this
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int pager_position) {
// show toast here for images
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
You can use these lines of code to detect the image on swipe
ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
System.out.println("Positoin is the=="+position);
if(position==0)
{
///on the zero position you can get the image
}
else
{
///on the first position you can get the image
}
}
};
There is a method yourViewpagerObject.getCurrentItem() which returns the position of currently Viewed page of view pager
I have an application that Implements ActionBarSherlock, it's mainly composed of
ViewPager with different content of fragments (for each page), with ViewPager indicator.
Here is my onCreate Method of the Activity that extends SherlockFragmentActivity
// Assume that tabs,sources,types are string arrays e.g. tabs = ["tab1","tab2","tab3"]
// types = ["listview","listview","webview"]
// according to the type of each tab, the type of content of the fragment associated to that tab is determined (e.g. WebView or ListView)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
srcContext = getBaseContext();
srcActivity = SaudiActivity.this;
int selectPos = 0;
Intent sender = getIntent();
FragmentPagerAdapter mAdapter = new NewsListAdapter(
getSupportFragmentManager());
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(mAdapter);
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(pager);
pager.setOffscreenPageLimit(tabs.length);
pager.setCurrentItem((tabs.length - 1));
currentPosition = (tabs.length - 1);
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPosition = position;
if ((type[position] == "listview" || type[position]
.equals("listview")) && loaded[position] == false) {
loaded[position] = true;
getNews(listViews[position], position);
}
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
getSupportActionBar().setCustomView(R.layout.logo);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
Context ctx = getSupportActionBar().getThemedContext();
SourcesAdapter adapter = new SourcesAdapter(ctx,
R.layout.navigation_list_item, src_name, icons, src_value);
}
Here are my News List Adapter (that creates the fragments),
public static class MyViewHolder {
public TextView title;
public ImageView icon;
}
class NewsListAdapter extends FragmentPagerAdapter {
public NewsListAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new NewsFragment(MyActivity.this, position);
}
// This is the number of pages -- 5
#Override
public int getCount() {
return tabs.length;
}
// This is the title of the page that will apppear on the "tab"
public CharSequence getPageTitle(int position) {
return tabs[position];
}
}
public List<NewsItem> NewsItems;
Finally here's my NewsFragment:
public static class NewsFragment extends Fragment {
private int position;
public NewsFragment() {
}
public NewsFragment(Context ctx, int pos) {
this.position = pos;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = null;
if (type[position].equals("listview")) {
// Put a ListView in the Fragment
} else {
// Put a WebView in the Fragment
}
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
Let the fragment handle it's state by overriding onSaveInstanceState and placing the necessary values into outState. Recover that state in onCreateView using savedInstanceState. Also I'm pretty sure that if you're using Actionbarsherlock fragments need to extend SherlockFragment rather than Fragment.
I am using view-pager.In that I have three tabs : 1. History , 2. Main , 3. Map .
I have stopwatch into main activity.When I press the start and then after stop at that time value of the stopwatch add into the sqlite DB. And into history activity I am fetching the value of stopwatch from DB and store into the listview. It's working perfect.
But now I want the update the History activity when I swipe from the Main > History so After press the stop button,I got the last value into listview of history activity.
My question is how can I update the view on swipe the viewpager?
public class SwipeyTabsSampleActivity extends FragmentActivity {
private static final String [] TITLES = {
"HISTORY",
"MAIN",
"MAP"
};
private SwipeyTabs mTabs;
private ViewPager mViewPager;
//Handler handler=new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipeytab);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
SwipeyTabsPagerAdapter adapter = new SwipeyTabsPagerAdapter(this,
getSupportFragmentManager());
mViewPager.setAdapter(adapter);
mTabs.setAdapter(adapter);
mViewPager.setOnPageChangeListener(mTabs);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(3);
}
private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements
SwipeyTabsAdapter, ViewPager.OnPageChangeListener {
private final Context mContext;
ViewPager viewpager;
public SwipeyTabsPagerAdapter(Context context, FragmentManager fm, ViewPager mViewPager) {
super(fm);
this.mContext = context;
viewpager = mViewPager;
//viewpager.setAdapter(this);
viewpager.setOnPageChangeListener(this);
}
#Override
public Fragment getItem(int position) {
Fragment f = new Fragment();
switch (position) {
case 0:
f = History.newInstance(position);
break;
case 1:
f = Main.newInstance(position);
break;
case 2:
f = Map.newInstance(position);
break;
}
return f;
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager pager = (ViewPager) container;
View view = (View) object;
pager.removeView(view);
}
public TextView getTab(final int position, SwipeyTabs root) {
TextView view = (TextView) LayoutInflater.from(mContext).inflate(
R.layout.swipey_tab_indicator, root, false);
view.setText(TITLES[position]);
view.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mViewPager.setCurrentItem(position);
}
});
return view;
}
#Override
public void onPageScrollStateChanged(int state) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int positiion) {
// TODO Auto-generated method stub
}
}
}
Add ViewPager OnPageChangeListener:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// your code here
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
This will affect the changes from one page to another page in view pager.
OnPageChangeListener pagechangelistener =new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Logger.logMessage("Called first");
pageAdapter.notifyDataSetChanged();
indicator.setCurrentItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Logger.logMessage("Called second");
}
#Override
public void onPageScrollStateChanged(int arg0) {
Logger.logMessage("Called third");
}
};
myViewPager.setOnPageChangeListener(pagechangelistener);
Use this in your page adapter.
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Take one string and add the Getters and setters into your FragmentActivity class.
Like...
String HistoryFragment;
public String getHistoryFragment() {
return HistoryFragment;
}
public void setHistoryFragment(String historyFragment) {
HistoryFragment = historyFragment;
}
Then after we can access another fragment from our current fragment by calling findFragmentByTag(<tag of target fragment>).
For the more information check the link Communication between Fragments in ViewPager.
Have you tried implementing OnPageChanged`? You can capture when the user start swiping.
do pager.setOnPageChanged(new ....) and Eclipse will show you the methods you can override.
Then you can override onPageScrollStateChanged(int state)
onPageScrollStateChanged(int state){
if (state==OnPageChangeListener.SCROLL_STATE_DRAGGING){
// update here
}
}