I have a problem when it will display a custom dialog, I mean the button that is in the fragment when I click will popup / dialog.
anyone help?
Fragment
public abstract class BaseFragment extends Fragment {
public Context context;
public Activity activity;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
//or
this.activity = (Activity) context;
}
}
Dialog
public class BaseDialog extends Dialog {
public Context context;
public Activity activity;
public LayoutInflater inflater;
public Window window;
public View decorView;
private final WindowManager.LayoutParams attributes;
public BaseDialog(Context context) {
super(context);
activity = (Activity) context;
this.context = context;
inflater = LayoutInflater.from(context);
window = getWindow();
//no title
assert window != null;
window.requestFeature(Window.FEATURE_NO_TITLE);
//auto dismiss dialog
setCanceledOnTouchOutside(true);
//decorView
decorView = window.getDecorView();
attributes = getWindow().getAttributes();
}
/**
* Transparency 0.0f - 1.0f
*
* #param f
*/
public void setDimAmount(float f) {
attributes.dimAmount = f;
getWindow().setAttributes(attributes);
}
/**
* #param gravity gravity
*/
public void setGravity(int gravity) {
window.setGravity(gravity);
}
/**
* dialog animation
*
* #param resId
*/
public void setAnimation(int resId) {
window.setWindowAnimations(resId);
}
/**
* custom view
*
* #param view
* #param width
* #param height
*/
public void setContentView(View view, int width, int height) {
super.setContentView(view);
window.setLayout(width, height);
}
}
PopupWindow
public class MyPopupWindow extends PopupWindow {
public MyPopupWindow(View contentView, int width, int height) {
super(contentView, width, height);
}
#Override
public void showAsDropDown(View anchor) {
if (Build.VERSION.SDK_INT >= 24) {
Rect rect = new Rect();
anchor.getGlobalVisibleRect(rect);
int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
setHeight(h);
}
super.showAsDropDown(anchor);
}
#Override
public void showAsDropDown(View anchor, int xoff, int yoff) {
if (Build.VERSION.SDK_INT >= 24) {
Rect rect = new Rect();
anchor.getGlobalVisibleRect(rect);
int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
setHeight(h);
}
super.showAsDropDown(anchor, xoff, yoff);
}
}
=== End ===
public class MyFragment extends BaseFragment {
public void onClick(View v) {
showDialog();
//or
showPup(v);
}
private void showDialog() {
new MyDialog(context).show();
new MyDialog(activity).show();
}
private void showPup(View v) {
MyPopupWindow popupWindow = new MyPopupWindow(v, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setTouchable(true);
popupWindow.setAnimationStyle(R.style.sealFragment_menu_animation);
popupWindow.showAsDropDown(view);
}
}
Related
I want to edit HideBottomViewOnScrollBehavior class so that it can be reversed
to work as HideTopViewOnScrollBehavior
this is the class code :
/** * The {#link Behavior} for a View within a {#link
CoordinatorLayout} to hide the view off the * bottom of the screen
when scrolling down, and show it when scrolling up. */
public class HideBottomViewOnScrollBehavior<V extends View> extends CoordinatorLayout.Behavior<V> {
protected static final int ENTER_ANIMATION_DURATION = 225;
protected static final int EXIT_ANIMATION_DURATION = 175;
private static final int STATE_SCROLLED_DOWN = 1;
private static final int STATE_SCROLLED_UP = 2;
private int height = 0;
private int currentState = STATE_SCROLLED_UP;
private int additionalHiddenOffsetY = 0;
#Nullable private ViewPropertyAnimator currentAnimator;
public HideBottomViewOnScrollBehavior() {}
public HideBottomViewOnScrollBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onLayoutChild(
#NonNull CoordinatorLayout parent, #NonNull V child, int layoutDirection) {
ViewGroup.MarginLayoutParams paramsCompat =
(ViewGroup.MarginLayoutParams) child.getLayoutParams();
height = child.getMeasuredHeight() + paramsCompat.bottomMargin;
return super.onLayoutChild(parent, child, layoutDirection);
}
/**
* Sets an additional offset for the y position used to hide the view.
*
* #param child the child view that is hidden by this behavior
* #param offset the additional offset in pixels that should be added when the view slides away
*/
public void setAdditionalHiddenOffsetY(#NonNull V child, #Dimension int offset) {
additionalHiddenOffsetY = offset;
if (currentState == STATE_SCROLLED_DOWN) {
child.setTranslationY(height + additionalHiddenOffsetY);
}
}
#Override
public boolean onStartNestedScroll(
#NonNull CoordinatorLayout coordinatorLayout,
#NonNull V child,
#NonNull View directTargetChild,
#NonNull View target,
int nestedScrollAxes,
int type) {
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL;
}
#Override
public void onNestedScroll(
CoordinatorLayout coordinatorLayout,
#NonNull V child,
#NonNull View target,
int dxConsumed,
int dyConsumed,
int dxUnconsumed,
int dyUnconsumed,
int type,
#NonNull int[] consumed) {
if (dyConsumed > 0) {
slideDown(child);
} else if (dyConsumed < 0) {
slideUp(child);
}
}
/** * Perform an animation that will slide the child from it's
current position to be totally on the * screen. */
public void slideUp(#NonNull V child) {
if (currentState == STATE_SCROLLED_UP) {
return;
}
if (currentAnimator != null) {
currentAnimator.cancel();
child.clearAnimation();
}
currentState = STATE_SCROLLED_UP;
animateChildTo(
child, 0, ENTER_ANIMATION_DURATION, AnimationUtils.LINEAR_OUT_SLOW_IN_INTERPOLATOR);
}
/** * Perform an animation that will slide the child from it's
current position to be totally off the * screen. */
public void slideDown(#NonNull V child) {
if (currentState == STATE_SCROLLED_DOWN) {
return;
}
if (currentAnimator != null) {
currentAnimator.cancel();
child.clearAnimation();
}
currentState = STATE_SCROLLED_DOWN;
animateChildTo(
child,
height + additionalHiddenOffsetY,
EXIT_ANIMATION_DURATION,
AnimationUtils.FAST_OUT_LINEAR_IN_INTERPOLATOR);
}
private void animateChildTo(
#NonNull V child, int targetY, long duration, TimeInterpolator interpolator) {
currentAnimator =
child
.animate()
.translationY(targetY)
.setInterpolator(interpolator)
.setDuration(duration)
.setListener(
new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
currentAnimator = null;
}
});
}
}
Can any one give me a source to learn about themes and animations in android?
I have a set of banner images that can slide when user slide it and touching image will redirect to some website..
I want to add auto scroll to the banner images, but I am not too sure how to do it, can anyone help me take a look at below code?
public class MyAdapter extends InfinitePagerAdapter {
BannerPagerAdapter pagerAdapter;
AutoScrollViewPager viewPager;
public static ArrayList<HashMap<String,String>> bannerAry = new ArrayList<HashMap<String,String>>();
public void onCreate(Bundle savedInstanceState) {
// Home header banner
LayoutInflater inflater = getLayoutInflater();
header = inflater.inflate(R.layout.home_banner, null);
if (homeBanner.equalsIgnoreCase("enable") && bannerAry.size() > 0){
gridView.addHeaderView(header);
}
viewPager = (AutoScrollViewPager) header.findViewById(R.id.view_pager);
pageIndicator = (LinePageIndicator) header.findViewById(R.id.indicator);
display = this.getWindowManager().getDefaultDisplay();
float scale = (float) display.getWidth() / Constants.HOME_BANNER_WIDTH;
int newHeight = (int) Math.round(Constants.HOME_BANNER_HEIGHT * scale);
viewPager.getLayoutParams().height = newHeight;
pagerAdapter = new BannerPagerAdapter(this, bannerAry);
viewPager.setAdapter(pagerAdapter);
pageIndicator.setViewPager(viewPager);
viewPager.addOnPageChangeListener(mOnPageChangeListener);
class BannerPagerAdapter extends PagerAdapter {
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String,String>> data;
public BannerPagerAdapter(Context act, ArrayList<HashMap<String,String>> newary) {
this.data = newary;
this.context = act;
}
public int getCount() {
return data.size();
}
public Object instantiateItem(ViewGroup collection, final int position) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.banner_image,
collection, false);
ImageView image = (ImageView) itemView.findViewById(R.id.image);
String img = data.get(position).get("image");
Log.v("banner img", "img="+img);
if (!img.equals("")){
Picasso.with(FragmentMainActivity.this).load(img).into(image);
}
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (Patterns.WEB_URL.matcher(data.get(position).get("url")).matches()) {
Intent b = new Intent(Intent.ACTION_VIEW, Uri.parse(data.get(position).get("url")));
startActivity(b);
} else {
Toast.makeText(FragmentMainActivity.this, getString(R.string.url_invalid), Toast.LENGTH_SHORT).show();
}
}
});
((ViewPager) collection).addView(itemView, 0);
return itemView;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int state) {
enableDisableSwipeRefresh( state == ViewPager.SCROLL_STATE_IDLE );
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
}
};
private void enableDisableSwipeRefresh(boolean enabled){
if (enabled) {
swipeLayout.setEnabled(true);
} else {
swipeLayout.setEnabled(false);
}
}
You can do this by using a TimerTask where you can schedule scroll events with some duration gap, you need to call this method after you have initialized the viewPager and pagerAdapter, here's the code:
private void startAutoScrolling() {
stopAutoScrolling();
TimerTask task = new TimerTask() {
#Override
public void run() {
if(activityContext!=null)
activityContext.runOnUiThread(new Runnable() {
#Override
public void run() {
int position = (viewPager.getCurrentItem() + 1) % pagerAdapter.getCount();
viewPager.setCurrentItem(position);
}
});
}
};
timer = new Timer();
timer.scheduleAtFixedRate(task, 3000, 3000);
}
here stopAutoScrolling() method it to make sure that you stop the previous running TimerTask for auto scroll which may be the case if the user returns to app after pressing the home button or taking a call.
public void stopAutoScrolling() {
Log.i(TAG, "stop auto scroll of viewpager");
if (timer != null)
timer.cancel();
}
How i can put icon in my tab using SlidingTabLayout. I just want to change the Titles into Icon. Please help me on how to do it.
Here is the code
ViewPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class ViewPagerAdapter 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 ViewPagerAdapter(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
{
OrderTab ordertab = new OrderTab();
return ordertab;
}
else if(position==1) // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
ViewOrderTab viewordertab = new ViewOrderTab();
return viewordertab;
}
else
{
OrderStatus orderstatus = new OrderStatus();
return orderstatus;
}
}
// 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;
}
public static interface FirstShot
{
public void onFirstShot();
}
}
SlidingTabLayout.java
package com.example.work.mcoatorderingapp;
import android.content.Context;
import android.graphics.Typeface;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* To be used with ViewPager to provide a tab indicator component which give constant feedback as to
* the user's scroll progress.
* <p>
* To use the component, simply add it to your view hierarchy. Then in your
* {#link android.app.Activity} or {#link android.support.v4.app.Fragment} call
* {#link #setViewPager(ViewPager)} providing it the ViewPager this layout is being used for.
* <p>
* The colors can be customized in two ways. The first and simplest is to provide an array of colors
* via {#link #setSelectedIndicatorColors(int...)}. The
* alternative is via the {#link TabColorizer} interface which provides you complete control over
* which color is used for any individual position.
* <p>
* The views used as tabs can be customized by calling {#link #setCustomTabView(int, int)},
* providing the layout ID of your custom layout.
*/
public class SlidingTabLayout extends HorizontalScrollView {
/**
* Allows complete control over the colors drawn in the tab layout. Set with
* {#link #setCustomTabColorizer(TabColorizer)}.
*/
public interface TabColorizer {
/**
* #return return the color of the indicator used when {#code position} is selected.
*/
int getIndicatorColor(int position);
}
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 12;
private int mTitleOffset;
private int mTabViewLayoutId;
private int mTabViewTextViewId;
private boolean mDistributeEvenly;
private ViewPager mViewPager;
private SparseArray<String> mContentDescriptions = new SparseArray<String>();
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
private final SlidingTabStrip mTabStrip;
public SlidingTabLayout(Context context) {
this(context, null);
}
public SlidingTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Disable the Scroll Bar
setHorizontalScrollBarEnabled(false);
// Make sure that the Tab Strips fills this View
setFillViewport(true);
mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
mTabStrip = new SlidingTabStrip(context);
addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
/**
* Set the custom {#link TabColorizer} to be used.
*
* If you only require simple custmisation then you can use
* {#link #setSelectedIndicatorColors(int...)} to achieve
* similar effects.
*/
public void setCustomTabColorizer(TabColorizer tabColorizer) {
mTabStrip.setCustomTabColorizer(tabColorizer);
}
public void setDistributeEvenly(boolean distributeEvenly) {
mDistributeEvenly = distributeEvenly;
}
/**
* Sets the colors to be used for indicating the selected tab. These colors are treated as a
* circular array. Providing one color will mean that all tabs are indicated with the same color.
*/
public void setSelectedIndicatorColors(int... colors) {
mTabStrip.setSelectedIndicatorColors(colors);
}
/**
* Set the {#link ViewPager.OnPageChangeListener}. When using {#link SlidingTabLayout} you are
* required to set any {#link ViewPager.OnPageChangeListener} through this method. This is so
* that the layout can update it's scroll position correctly.
*
* #see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
*/
public void OnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mViewPagerPageChangeListener = listener;
}
/**
* Set the custom layout to be inflated for the tab views.
*
* #param layoutResId Layout id to be inflated
* #param textViewId id of the {#link TextView} in the inflated view
*/
public void setCustomTabView(int layoutResId, int textViewId) {
mTabViewLayoutId = layoutResId;
mTabViewTextViewId = textViewId;
}
/**
* Sets the associated view pager. Note that the assumption here is that the pager content
* (number of tabs and tab titles) does not change after this call has been made.
*/
public void setViewPager(ViewPager viewPager) {
mTabStrip.removeAllViews();
mViewPager = viewPager;
if (viewPager != null) {
viewPager.setOnPageChangeListener(new InternalViewPagerListener());
populateTabStrip();
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {#link #setCustomTabView(int, int)}.
*/
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
textView.setAllCaps(true);
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
private void populateTabStrip() {
final PagerAdapter adapter = mViewPager.getAdapter();
final View.OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
TextView tabTitleView = null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
if (mDistributeEvenly) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
lp.width = 0;
lp.weight = 1;
}
tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
String desc = mContentDescriptions.get(i, null);
if (desc != null) {
tabView.setContentDescription(desc);
}
mTabStrip.addView(tabView);
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
}
tabTitleView.setTextColor(getResources().getColorStateList(R.color.selector));
tabTitleView.setTextSize(14);
}
}
public void setContentDescription(int i, String desc) {
mContentDescriptions.put(i, desc);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mViewPager != null) {
scrollToTab(mViewPager.getCurrentItem(), 0);
}
}
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
private int mScrollState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
mTabStrip.getChildAt(i).setSelected(position == i);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
}
private class TabClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i)) {
mViewPager.setCurrentItem(i);
return;
}
}
}
}
}
The Fragments are OrderTab.java the same code with ViewOrderTab.java and OrderStatus.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OrderStatus extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.orderstatus_list,container,false);
return v;
}
}
MainActivity.java
EditText search;
ProgressDialog pDialog;
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"Order Product", "Cart", "Order Status"};
int Numboftabs = 3;
String titlebar;
#Override
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);
Try
private int[] imageResId = {
R.drawable.ic_home,
R.drawable.ic_my_timeline,
R.drawable.ic_my_pages,
R.drawable.ic_my_groups,
R.drawable.ic_liked_pages
};
#Override
public CharSequence getPageTitle(int position) {
Drawable image = mContext.getResources().getDrawable(imageResId[position]);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
SpannableString sb = new SpannableString(" ");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
instead of
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
in your ViewPagerAdapter class.
EDIT1:
In your activity change
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
to
adapter = new ViewPagerAdapter(this, getSupportFragmentManager(), Titles, Numboftabs);
Then in your ViewPagerAdapter following changes are needed.
Context mContext;
public ViewPagerAdapter(Context context, FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.mContext = context;
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
EDIT2:
try extending FragmentPagerAdapter instead of FragmentStatePagerAdapter in your ViewPagerAdapter.
In your main activity code should be this:
tabs=(SlidingTabLayout)findViewById(R.id.tabs);
tabs.setCustomTabView(R.layout.custom_tab, 0);
Here is custom_tab.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textStyle="bold"
android:background="?android:selectableItemBackground"
android:padding="16dp"
android:gravity="center" />
hope this helps!
I am using SwipeableRecyclerView and I was wondering how I can disable left swipe?
This is my code:
MainActivity.class
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.github.brnunes.swipeablerecyclerview.SwipeableRecyclerViewTouchListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private CardViewAdapter mAdapter;
private ArrayList<String> mItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mItems = new ArrayList<>(30);
for (int i = 0; i < 30; i++) {
mItems.add(String.format("Card number %02d", i));
}
OnItemTouchListener itemTouchListener = new OnItemTouchListener() {
#Override
public void onCardViewTap(View view, int position) {
Toast.makeText(MainActivity.this, "Tapped " + mItems.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onButton1Click(View view, int position) {
Toast.makeText(MainActivity.this, "Clicked Button1 in " + mItems.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onButton2Click(View view, int position) {
Toast.makeText(MainActivity.this, "Clicked Button2 in " + mItems.get(position), Toast.LENGTH_SHORT).show();
}
};
mAdapter = new CardViewAdapter(mItems, itemTouchListener);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(recyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
#Override
public boolean canSwipe(int position) {
return true;
}
#Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
// Toast.makeText(MainActivity.this, mItems.get(position) + " swiped left", Toast.LENGTH_SHORT).show();
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
// Toast.makeText(MainActivity.this, mItems.get(position) + " swiped right", Toast.LENGTH_SHORT).show();
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
});
recyclerView.addOnItemTouchListener(swipeTouchListener);
}
/**
* Interface for the touch events in each item
*/
public interface OnItemTouchListener {
/**
* Callback invoked when the user Taps one of the RecyclerView items
*
* #param view the CardView touched
* #param position the index of the item touched in the RecyclerView
*/
public void onCardViewTap(View view, int position);
/**
* Callback invoked when the Button1 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the RecyclerView
*/
public void onButton1Click(View view, int position);
/**
* Callback invoked when the Button2 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the RecyclerView
*/
public void onButton2Click(View view, int position);
}
/**
* A simple adapter that loads a CardView layout with one TextView and two Buttons, and
* listens to clicks on the Buttons or on the CardView
*/
public class CardViewAdapter extends RecyclerView.Adapter<CardViewAdapter.ViewHolder> {
private List<String> cards;
private OnItemTouchListener onItemTouchListener;
public CardViewAdapter(List<String> cards, OnItemTouchListener onItemTouchListener) {
this.cards = cards;
this.onItemTouchListener = onItemTouchListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view_layout, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.title.setText(cards.get(i));
}
#Override
public int getItemCount() {
return cards == null ? 0 : cards.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private Button button1;
private Button button2;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.card_view_title);
button1 = (Button) itemView.findViewById(R.id.card_view_button1);
button2 = (Button) itemView.findViewById(R.id.card_view_button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemTouchListener.onButton1Click(v, getPosition());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemTouchListener.onButton2Click(v, getPosition());
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemTouchListener.onCardViewTap(v, getPosition());
}
});
}
}
}
}
SwipeableRecyclerViewTouchListener.class
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A {#link View.OnTouchListener} that makes the list items in a {#link android.support.v7.widget.RecyclerView}
* dismissable by swiping.
* <p/>
* <p>Example usage:</p>
* <p/>
* <pre>
* SwipeDismissRecyclerViewTouchListener touchListener =
* new SwipeDismissRecyclerViewTouchListener(
* listView,
* new SwipeDismissRecyclerViewTouchListener.OnDismissCallback() {
* public void onDismiss(ListView listView, int[] reverseSortedPositions) {
* for (int position : reverseSortedPositions) {
* adapter.remove(adapter.getItem(position));
* }
* adapter.notifyDataSetChanged();
* }
* });
* listView.setOnTouchListener(touchListener);
* listView.setOnScrollListener(touchListener.makeScrollListener());
* </pre>
* <p/>
* <p>This class Requires API level 12 or later due to use of {#link
* android.view.ViewPropertyAnimator}.</p>
*/
public class SwipeableRecyclerViewTouchListener implements RecyclerView.OnItemTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
private RecyclerView mRecyclerView;
private SwipeListener mSwipeListener;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private List<PendingDismissData> mPendingDismisses = new ArrayList<>();
private int mDismissAnimationRefCount = 0;
private float mAlpha;
private float mDownX;
private float mDownY;
private boolean mSwiping;
private int mSwipingSlop;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private int mAnimatingPosition = ListView.INVALID_POSITION;
private View mDownView;
private boolean mPaused;
private float mFinalDelta;
/**
* Constructs a new swipe touch listener for the given {#link android.support.v7.widget.RecyclerView}
*
* #param recyclerView The recycler view whose items should be dismissable by swiping.
* #param listener The listener for the swipe events.
*/
public SwipeableRecyclerViewTouchListener(RecyclerView recyclerView, SwipeListener listener) {
ViewConfiguration vc = ViewConfiguration.get(recyclerView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = recyclerView.getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
mRecyclerView = recyclerView;
mSwipeListener = listener;
/**
* This will ensure that this SwipeableRecyclerViewTouchListener is paused during list view scrolling.
* If a scroll listener is already assigned, the caller should still pass scroll changes through
* to this listener.
*/
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
setEnabled(newState != RecyclerView.SCROLL_STATE_DRAGGING);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
}
});
}
/**
* Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures.
*
* #param enabled Whether or not to watch for gestures.
*/
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent motionEvent) {
return handleTouchEvent(motionEvent);
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent motionEvent) {
handleTouchEvent(motionEvent);
}
private boolean handleTouchEvent(MotionEvent motionEvent) {
if (mViewWidth < 2) {
mViewWidth = mRecyclerView.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
if (mPaused) {
break;
}
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mRecyclerView.getChildCount();
int[] listViewCoords = new int[2];
mRecyclerView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
for (int i = 0; i < childCount; i++) {
child = mRecyclerView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
mDownView = child;
break;
}
}
if (mDownView != null && mAnimatingPosition != mRecyclerView.getChildPosition(mDownView)) {
mAlpha = mDownView.getAlpha();
mDownX = motionEvent.getRawX();
mDownY = motionEvent.getRawY();
mDownPosition = mRecyclerView.getChildPosition(mDownView);
if (mSwipeListener.canSwipe(mDownPosition)) {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
} else {
mDownView = null;
}
}
break;
}
case MotionEvent.ACTION_CANCEL: {
if (mVelocityTracker == null) {
break;
}
if (mDownView != null && mSwiping) {
// cancel
mDownView.animate()
.translationX(0)
.alpha(mAlpha)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownY = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_UP: {
if (mVelocityTracker == null) {
break;
}
mFinalDelta = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (Math.abs(mFinalDelta) > mViewWidth / 2 && mSwiping) {
dismiss = true;
dismissRight = mFinalDelta > 0;
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
&& absVelocityY < absVelocityX && mSwiping) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityX < 0) == (mFinalDelta < 0);
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss && mDownPosition != mAnimatingPosition && mDownPosition != ListView.INVALID_POSITION) {
// dismiss
final View downView = mDownView; // mDownView gets null'd before animation ends
final int downPosition = mDownPosition;
++mDismissAnimationRefCount;
mAnimatingPosition = mDownPosition;
mDownView.animate()
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
performDismiss(downView, downPosition);
}
});
} else {
// cancel
mDownView.animate()
.translationX(0)
.alpha(mAlpha)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownY = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker == null || mPaused) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
float deltaY = motionEvent.getRawY() - mDownY;
if (!mSwiping && Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
mSwiping = true;
mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
}
if (mSwiping) {
mDownView.setTranslationX(deltaX - mSwipingSlop);
mDownView.setAlpha(Math.max(0f, Math.min(mAlpha,
mAlpha * (1f - Math.abs(deltaX) / mViewWidth))));
return true;
}
break;
}
}
return false;
}
private void performDismiss(final View dismissView, final int dismissPosition) {
// Animate the dismissed list item to zero-height and fire the dismiss callback when
// all dismissed list item animations have completed. This triggers layout on each animation
// frame; in the future we may want to do something smarter and more performant.
final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
final int originalLayoutParamsHeight = lp.height;
final int originalHeight = dismissView.getHeight();
ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
--mDismissAnimationRefCount;
if (mDismissAnimationRefCount == 0) {
// No active animations, process all pending dismisses.
// Sort by descending position
Collections.sort(mPendingDismisses);
int[] dismissPositions = new int[mPendingDismisses.size()];
for (int i = mPendingDismisses.size() - 1; i >= 0; i--) {
dismissPositions[i] = mPendingDismisses.get(i).position;
}
if (mFinalDelta > 0) {
mSwipeListener.onDismissedBySwipeRight(mRecyclerView, dismissPositions);
} else {
mSwipeListener.onDismissedBySwipeLeft(mRecyclerView, dismissPositions);
}
// Reset mDownPosition to avoid MotionEvent.ACTION_UP trying to start a dismiss
// animation with a stale position
mDownPosition = ListView.INVALID_POSITION;
ViewGroup.LayoutParams lp;
for (PendingDismissData pendingDismiss : mPendingDismisses) {
// Reset view presentation
pendingDismiss.view.setAlpha(mAlpha);
pendingDismiss.view.setTranslationX(0);
lp = pendingDismiss.view.getLayoutParams();
lp.height = originalLayoutParamsHeight;
pendingDismiss.view.setLayoutParams(lp);
}
// Send a cancel event
long time = SystemClock.uptimeMillis();
MotionEvent cancelEvent = MotionEvent.obtain(time, time,
MotionEvent.ACTION_CANCEL, 0, 0, 0);
mRecyclerView.dispatchTouchEvent(cancelEvent);
mPendingDismisses.clear();
mAnimatingPosition = ListView.INVALID_POSITION;
}
}
});
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
lp.height = (Integer) valueAnimator.getAnimatedValue();
dismissView.setLayoutParams(lp);
}
});
mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
animator.start();
}
/**
* The callback interface used by {#link SwipeableRecyclerViewTouchListener} to inform its client
* about a swipe of one or more list item positions.
*/
public interface SwipeListener {
/**
* Called to determine whether the given position can be swiped.
*/
boolean canSwipe(int position);
/**
* Called when the item has been dismissed by swiping to the left.
*
* #param recyclerView The originating {#link android.support.v7.widget.RecyclerView}.
* #param reverseSortedPositions An array of positions to dismiss, sorted in descending
* order for convenience.
*/
void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions);
/**
* Called when the item has been dismissed by swiping to the right.
*
* #param recyclerView The originating {#link android.support.v7.widget.RecyclerView}.
* #param reverseSortedPositions An array of positions to dismiss, sorted in descending
* order for convenience.
*/
void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions);
}
class PendingDismissData implements Comparable<PendingDismissData> {
public int position;
public View view;
public PendingDismissData(int position, View view) {
this.position = position;
this.view = view;
}
#Override
public int compareTo(#NonNull PendingDismissData other) {
// Sort by descending position
return other.position - position;
}
}
}
Use simple recyclerView and then You can use ItemTouchHelper.Callback
public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
private final YourAdapter mAdapter;
public SimpleItemTouchHelperCallback(YourAdapter adapter) {
mAdapter = adapter;
}
#Override
public boolean isLongPressDragEnabled() {
return true;
}
#Override
public boolean isItemViewSwipeEnabled() {
return true;
}
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(dragFlags, swipeFlags);
}
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}
}
In YourAdapter class which is extending recyclerview adapter add these functions.
public void onItemMove(int oldPosition, int newPosition) {
notifyItemMoved(oldPosition,newPosition);
}
public void onItemDismiss(int adapterPosition) {
/// here you can delete from the array and notify for that specific position
}
ItemTouchHelper provides some flags which you can see here
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(dragFlags, swipeFlags);
}
If you want to disable Left to Right Swipe just remove ItemTouchHelper.START flag.
If you want to disable Right to Left Swipe just remove ItemTouchHelper.END flag.
You can pass 0 value instead of swipeFlags. Swipe will not work.
Same goes for dragFlags.
I have implemented this as well and it works like a charm ;) Happy Coding <3
I have viewpager in my main activity and i need set timer to it to
automatically change slide .
I need set defult size and position to my image ( any resolution) for any screen to show one third of my top screen like this Preview.
Mainactivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Image slide show
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
// End Image slide show
}
ImageAdapter.java
package com.example.gallery;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
For timer,
in the main activity add these after viewPager.setAdapter(adapter);
myPager.setCurrentItem(0);
pagerAdapter.setTimer(myPager,7);
in the pager adapter class
//gloabals
final Handler handler = new Handler();
public Timer swipeTimer ;
/**
* this function swipes pages left to right for every 7 seconds
* #param myPager its viewpager.
* #param time as second, for 7 second enter 7
*
*/
public void setTimer(final ViewPager myPager, int time){
final int size =objects.size();
final Runnable Update = new Runnable() {
int NUM_PAGES =size;
int currentPage = 0 ;
public void run() {
if (currentPage == NUM_PAGES ) {
currentPage = 0;
}
myPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 1000, time*1000);
}
or you can use this one
/**
* this function swipes pages left to right for every 7 seconds
* #param myPager
* #param time
* #param numPages we recommend that it should be as much as much objects.size()
* #param curPage we recommend that it should start from 0
*
*/
public void setTimer(final ViewPager myPager, int time, final int numPages, final int curPage){
final Runnable Update = new Runnable() {
int NUM_PAGES =numPages;
int currentPage = curPage ;
public void run() {
if (currentPage == NUM_PAGES ) {
currentPage = 0;
}
myPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 1000, time*1000);
}
this is for stopping timer
/**
* its kills runnable
*/
public void stopTimer(){
//handler.removeCallbacks(null);
swipeTimer.cancel();
}