I have a ViewPager that loads images from a remote server. My problem is, I don't know how to give it a function once a specific position is selected (not clicked). Let's say, I swipe the view pager until it reaches the specific image like image number 5, I want to show some Toast saying "image 5".
pager.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheOnDisc()
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(pagerPosition);
}
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
public void finishUpdate(View container) {
}
public int getCount() {
return images.length;
}
public Object instantiateItem(View view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
public void onLoadingFailed(FailReason failReason) {
String message = null;
switch (failReason) {
case IO_ERROR:
message = "Input/Output error";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
public void onLoadingComplete(Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
public void onLoadingCancelled() {
// Do nothing
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
public void restoreState(Parcelable state, ClassLoader loader) {
}
public Parcelable saveState() {
return null;
}
public void startUpdate(View container) {
}
}
}
You can implement onPageChangeListener, Than you can set this pageChageListener to your ViewPager using (setOnPageChangeListener()) ...
public class ImagePagerActivity extends BaseActivity implements onPageChangeListener {
private ViewPager pager;
// other variables here
public void onCreate(Bundle savedInstanceState) {
// create view Pager
// other variables
pager.setOnPageChangeListener(this);
}
// methods for Page Change Listener
#Override
public void onPageSelected(int pos) {
if (pos==5) {
//show Toast here
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// do Nothing
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// do Noting
}
}// class def ends here
edit..
Use this short hand version
Pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
if (pos==5) {
//show Toast here
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Overridee3public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
You should use the OnPageChangeListener.
There is as onPageSelected(int position) method that you can use to get the current position.
Something like
pager.setOnPageChangeListener(this);
Then make your ImagePagerActivity implement the OnPageChangeListener interface :
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
Toast.makeText(getApplicationContext(), "image " + position, Toast.LENGTH_SHORT).show();
}
public void onPageScrollStateChanged(int state) {
}
Related
Development environment
android phone version : 5.0(lollipop)
development tool : ADT(Build : v22.0.0-675183)
my app's minSdkVersion : API13
Problem Description
I use the slide menu library(open source : github.com/jfeinstein10/SlidingMenu).
The main layout consists of a [ListView] with [ViewPager] and [Left Slide Menu].
Before I open the left slide menu, it functions manually.
However, a scroll of listview and a swipe event in viewpager do not operate well after opening the left slide menu.
To expatiate on this, the event function is shown in logcat by calling program but the screen does not move.
Please answer if you know it.
My Code
public class AndroidTestActivity extends FlagmentActivity implements OnPageChangeListener, OnClickListener {
private ListView listView;
private ViewPager mPager;
private SlidingMenu menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
mAdapter = new MainListAdapter(this);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
...
}
});
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(new MyPagerAdapter(getApplicationContext()));
menu = new SlidingMenu(this);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.15f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setMenu(R.layout.menu_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.menu_frame, new LeftSlideMenuListFragment(MainMenuActivity.this))
.commit();
}
private class MyPagerAdapter extends PagerAdapter {
private LayoutInflater mInflater;
public MyPagerAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return 2;
}
#Override
public Object instantiateItem(View pager, int position) {
View v = null;
if(position==0) {
v = mInflater.inflate(R.layout.main_menu_01, null);
...
} else if(position==1) {
v = mInflater.inflate(R.layout.main_menu_02, null);
...
}
((ViewPager)pager).addView(v, 0);
return v;
}
#Override
public void destroyItem(View pager, int position, Object view) {
((ViewPager)pager).removeView((View)view);
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override public void finishUpdate(View arg0) { }
#Override public void restoreState(Parcelable arg0, ClassLoader arg1) {}
#Override public Parcelable saveState() { return null; }
#Override public void startUpdate(View arg0) {}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
#Override
public void onPageScrollStateChanged(int arg0) {}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
#Override
public void onPageSelected(int position) {}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if(menu.isMenuShowing()) {
menu.showContent();
mPager.getAdapter().notifyDataSetChanged();
mPager.invalidate();
} else {
finish();
}
}
return false;
}
}
I made an app which has 100 pages and change through swipe, but I want to add "Go to page" option so I can go to the specific page easily.
public class ViewPagerExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpager_example);
ExtendedViewPager mViewPager = (ExtendedViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());
}
static class TouchImageAdapter extends PagerAdapter {
private static int[] images = { R.drawable.page3, R.drawable.page4,
R.drawable.page5, R.drawable.page6, R.drawable.page7,
R.drawable.page8, R.drawable.page9, R.drawable.page10, R.drawable.page11,
R.drawable.page12, R.drawable.page13, R.drawable.page14,
R.drawable.page15, R.drawable.page16, R.drawable.page17,
R.drawable.page18, R.drawable.page19, R.drawable.page20, R.drawable.page21,
R.drawable.page22, R.drawable.page23, R.drawable.page24,
R.drawable.page25, R.drawable.page26, R.drawable.page27,
R.drawable.page28, R.drawable.page29, R.drawable.page30,
R.drawable.page31, R.drawable.page32, R.drawable.page33, R.drawable.page34,
R.drawable.page35, R.drawable.page36, R.drawable.page37,
R.drawable.page38, R.drawable.page39, R.drawable.page40, R.drawable.page41,
R.drawable.page42, R.drawable.page43, R.drawable.page44,
R.drawable.page45, R.drawable.page46, R.drawable.page47,
R.drawable.page48, R.drawable.page49, R.drawable.page50, R.drawable.page51,
R.drawable.page52, R.drawable.page53, R.drawable.page54,
R.drawable.page55, R.drawable.page56, R.drawable.page57,
R.drawable.page58, R.drawable.page59, R.drawable.page60, R.drawable.page61,
R.drawable.page62, R.drawable.page63, R.drawable.page64,
R.drawable.page65, R.drawable.page66, R.drawable.page67,
R.drawable.page68, R.drawable.page69, R.drawable.page70, R.drawable.page71,
R.drawable.page72, R.drawable.page73, R.drawable.page74 };
#Override
public int getCount() {
return images.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
TouchImageView img = new TouchImageView(container.getContext());
img.setImageResource(images[position]);
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
long lastPress;
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
if (interstitial.isLoaded())
interstitial.show();
}
}
To switch the ViewPager to a specific page, you just need to call setCurrentItem().
everybody I have a problerm when I put a PreferenceActivity in a TabHost.The PreferenceActivity cannot show,other Atcitivites whice in TabHost can show normally,And I have tested the PreferenceActivity independently,It can show normally, I have search the problerm by google,and I dinn't get the answer,anyone wound tell me the reason? thanks.
My TobHostAcitvity code is like this:
public class TabsActivity extends Activity {
protected static final String tag = "maps";
Context context = null;
LocalActivityManager manager = null;
ViewPager pager = null;
TabHost tabHost = null;
protected int currentItemId;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs_pager);
manager = new LocalActivityManager(this, true);
manager.dispatchCreate(savedInstanceState);
context = TabsActivity.this;
initiaTabHost();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
private View getView(String id, Intent intent) {
return manager.startActivity(id, intent).getDecorView();
}
public void initiaTabHost() {
tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setup();
tabHost.setup(manager);
Intent it1 = new Intent(context, WifiSearchAcitivity.class);
it1.putExtra("name", WifiSearchAcitivity.tag);
Intent it2 = new Intent(context, MapActivity.class);
it2.putExtra("name", MapActivity.tag);
Intent it3 = new Intent(context, MyPreferenceActivity.class);
it3.putExtra("name", MyPreferenceActivity.tag);
tabHost.addTab(tabHost.newTabSpec("列表").setIndicator("列表")
.setContent(it1));
tabHost.addTab(tabHost.newTabSpec("地图").setIndicator("地图")
.setContent(it2));
tabHost.addTab(tabHost.newTabSpec("设置").setIndicator("设置")
.setContent(it3));
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
log(tag, "onTabChange called id= " + tabId);
if (WifiSearchAcitivity.tag.equals(tabId)) {
pager.setCurrentItem(0);
} else if (MapActivity.tag.equals(tabId)) {
pager.setCurrentItem(1);
} else if (MyPreferenceActivity.tag.equals(tabId)) {
pager.setCurrentItem(2);
}
}
});
pager = (ViewPager) findViewById(R.id.viewpage);
final ArrayList<View> list = new ArrayList<View>();
list.add(getView(WifiSearchAcitivity.tag, it1));
list.add(getView(MapActivity.tag ,it2));
list.add(getView(MyPreferenceActivity.tag ,it3));
pager.setAdapter(new PagerAdapter() {
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
/*
* log(tag, "destroyItem called arg1="+arg1); ViewPager
* pViewPager = ((ViewPager) arg0);
* pViewPager.removeView(list.get(arg1));
*/
}
#Override
public void finishUpdate(View arg0) {
log(tag, "finishupdate called");
}
#Override
public int getCount() {
// log(tag, "getcount called");
return list.size();
}
#Override
public Object instantiateItem(ViewGroup arg0, int arg1) {
log(tag, " instantiateItem called arg1= " + arg1);
ViewPager pViewPager = ((ViewPager) arg0);
if (pViewPager.getChildCount() == 0) {// pViewPager.removeAllViews();
for (View view : list) {
pViewPager.addView(view);
}
}
return list.get(arg1);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
// log(tag, "isViewfromObject called " + (arg0 == arg1));
return arg0 == arg1;
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View arg0) {
}
});
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
log(tag, "onPageChangeListener called " + arg0);
currentItemId = arg0;
tabHost.setCurrentTab(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
}
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
}
}
I am using ViewPager to retrieve images from remote server. Everything is working well, but the problem is I don't know how to implement pinch Zoom in/out function to it. My code is below
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheOnDisc()
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(pagerPosition);
}
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
public void finishUpdate(View container) {
}
public int getCount() {
return images.length;
}
public Object instantiateItem(View view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
public void onLoadingFailed(FailReason failReason) {
String message = null;
switch (failReason) {
case IO_ERROR:
message = "Input/Output error";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
public void onLoadingComplete(Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
public void onLoadingCancelled() {
// Do nothing
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
public void restoreState(Parcelable state, ClassLoader loader) {
}
public Parcelable saveState() {
return null;
}
public void startUpdate(View container) {
}
}
}
if your viewpager is using an imageView then you can use touchImageView
https://github.com/MikeOrtiz/TouchImageView/blob/master/src/com/example/touch/TouchImageView.java
just replace your current imageview with this custom view. goodluck