Can't create a View Pager - android

I want to create a ViewPager, but when I execute the application in my phone, it shows me a blank activity and then the following error message:
The application testViewPager (process com.example.testviewpager) has stopped unexpectedly. Please try again.
How can I go about fixing this problem?
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">
<com.example.testviewpager.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#CCC">
<android.support.v4.view.ViewPager
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal" />
</com.example.testviewpager.PagerContainer>
</RelativeLayout>
PagerActivity.java:
public class PagerActivity extends Activity {
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
//Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
//A little space between pages
pager.setPageMargin(15);
//If hardware acceleration is enabled, you should also remove
// clipping on the pager for its children.
pager.setClipChildren(false);
}
//Nothing special about this adapter, just throwing up colored views for demo
private class MyPagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView view = new TextView(PagerActivity.this);
view.setText("Item "+position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50, position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}
}
PagerContainer.java:
public class PagerContainer extends FrameLayout implements ViewPager.OnPageChangeListener {
private ViewPager mPager;
boolean mNeedsRedraw = false;
public PagerContainer(Context context) {
super(context);
init();
}
public PagerContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagerContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setClipChildren(false);
}
#Override
protected void onFinishInflate() {
try {
mPager = (ViewPager) getChildAt(0);
mPager.setOnPageChangeListener(this);
} catch (Exception e) {
throw new IllegalStateException("The root child of PagerContainer must be a ViewPager");
}
}
public ViewPager getViewPager() {
return mPager;
}
private Point mCenter = new Point();
private Point mInitialTouch = new Point();
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCenter.x = w / 2;
mCenter.y = h / 2;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
//We capture any touches not already handled by the ViewPager
// to implement scrolling from a touch outside the pager bounds.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialTouch.x = (int)ev.getX();
mInitialTouch.y = (int)ev.getY();
default:
ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y - mInitialTouch.y);
break;
}
return mPager.dispatchTouchEvent(ev);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Force the container to redraw on scrolling.
//Without this the outer pages render initially and then stay static
if (mNeedsRedraw) invalidate();
}
#Override
public void onPageSelected(int position) { }
#Override
public void onPageScrollStateChanged(int state) {
mNeedsRedraw = (state != ViewPager.SCROLL_STATE_IDLE);
}
}
MainActivity.java:
public class MainActivity extends Activity
{
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
// Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
// A little space between pages
pager.setPageMargin(15);
}
// Nothing special about this adapter, just throwing up colored views for
// demo
private class MyPagerAdapter extends PagerAdapter
{
#Override
public Object instantiateItem(ViewGroup container, int position)
{
TextView view = new TextView(MainActivity.this);
view.setText("Item " + position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50,
position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((View) object);
}
#Override
public int getCount()
{
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return (view == object);
}
}
}

Related

Viewpager page not expanding on button click

I have a page in viewpager which have a button and a few views which are hidden by default. On click of the button, the views are to be toggled(Show/Hide). My issue is button click is working, but viewpager's height does not changes.
This is the code for adapter:
public class HomeCategoryAdapter extends PagerAdapter implements View.OnClickListener {
private LayoutInflater inflater;
private View lin_view_more, lin_view_less, lin_view_1, lin_view_2, lin_view_3, lin_view_4;
private WrapContentViewPager pager;
public HomeCategoryAdapter(Context context) {
this.mContext = context;
this.inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return 5;
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
pager = (EnhancedWrapContentViewPager) container;
View itemView = inflater.inflate(R.layout.homescreen_category_adapter, container, false);
...
lin_view_more = itemView.findViewById(R.id.lin_view_more);
lin_view_more.setOnClickListener(this);
lin_view_1 = itemView.findViewById(R.id.lin_view_1);
lin_view_1.setOnClickListener(this);
lin_view_2 = itemView.findViewById(R.id.lin_view_2);
lin_view_2.setOnClickListener(this);
lin_view_3 = itemView.findViewById(R.id.lin_view_3);
lin_view_3.setOnClickListener(this);
lin_view_4 = itemView.findViewById(R.id.lin_view_4);
lin_view_4.setOnClickListener(this);
switch (position) {
case 0:
parent_1.setVisibility(View.VISIBLE);
parent_2.setVisibility(View.GONE);
parent_3.setVisibility(View.GONE);
parent_4.setVisibility(View.GONE);
parent_5.setVisibility(View.GONE);
break;
case 1:
parent_1.setVisibility(View.GONE);
parent_2.setVisibility(View.VISIBLE);
parent_3.setVisibility(View.GONE);
parent_4.setVisibility(View.GONE);
parent_5.setVisibility(View.GONE);
break;
case 2:
parent_1.setVisibility(View.GONE);
parent_2.setVisibility(View.GONE);
parent_3.setVisibility(View.VISIBLE);
parent_4.setVisibility(View.GONE);
parent_5.setVisibility(View.GONE);
break;
case 3:
parent_1.setVisibility(View.GONE);
parent_2.setVisibility(View.GONE);
parent_3.setVisibility(View.GONE);
parent_4.setVisibility(View.VISIBLE);
parent_5.setVisibility(View.GONE);
break;
case 4:
parent_1.setVisibility(View.GONE);
parent_2.setVisibility(View.GONE);
parent_3.setVisibility(View.GONE);
parent_4.setVisibility(View.GONE);
parent_5.setVisibility(View.VISIBLE);
break;
}
...
((WrapContentViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((WrapContentViewPager) container).removeView((View) object);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.lin_view_more:
lin_view_more.setVisibility(View.GONE);
lin_view_1.setVisibility(View.VISIBLE);
lin_view_2.setVisibility(View.VISIBLE);
lin_view_3.setVisibility(View.VISIBLE);
lin_view_4.setVisibility(View.VISIBLE);
lin_view_less.setVisibility(View.VISIBLE);
if (pager != null) {
pager.measureView();
}
break;
case R.id.lin_view_less:
lin_view_more.setVisibility(View.VISIBLE);
lin_view_1.setVisibility(View.GONE);
lin_view_2.setVisibility(View.GONE);
lin_view_3.setVisibility(View.GONE);
lin_view_4.setVisibility(View.GONE);
lin_view_less.setVisibility(View.GONE);
if (pager != null) {
pager.post(new Runnable() {
#Override
public void run() {
pager.measureView();
}
});
}
break;
}
}
}
This is the code for modified view pager to make it wrap_content:
public class WrapContentViewPager extends ViewPager {
public WrapContentViewPager (Context context) {
super(context);
}
public WrapContentViewPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mode = MeasureSpec.getMode(heightMeasureSpec);
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int childMeasuredHeight = child.getMeasuredHeight();
if (childMeasuredHeight > height) {
Log.debugMessage("WrapContentViewPager", "page height updated");
height = childMeasuredHeight;
}
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public void measureView(){
requestLayout();
}
}
As shown in onClick above, I am calling requestLayout() on pager. The page height gets calculated but the layout is not expanding.
Update:
If I swipe to another page(3rd or 4th) then go back to this page, show/hide are working fine.
Not getting why is it not working.
Can you add this code after requestLayout();code line:
invalidate();
if it doesn't work also can you try this:
postInvalidate();
For what these code lines do, you can take a look at this:
What does postInvalidate() do?

How to dynamically set the height of viewpager in android

I have read and tried a lot of works on the way to set the view pager to obtain a dynamic height buh to no avail. After setting the below, the screen was divided half and the list of data was scrolling from the middle of the screen.
CustomPager
public class CustomPager extends ViewPager {
private View mCurrentView;
public CustomPager(Context context) {
super(context);
}
public CustomPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mCurrentView == null) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
int height = 0;
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = mCurrentView.getMeasuredHeight();
if (h > height) height = h;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
CustomScrollView
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
HomePage
public class HomePage extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private int[] tabIcons = {
R.drawable.ic_tab_favourite,
R.drawable.ic_tab_call,
R.drawable.ic_tab_contacts
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_view_icon_text_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(3);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(1).select();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new One(), "One");
adapter.addFrag(new Two(), "Two");
adapter.addFrag(new Three(), "Three");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private int mCurrentPosition = -1;
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position != mCurrentPosition) {
Fragment fragment = (Fragment) object;
CustomPager pager = (CustomPager) container;
if (fragment != null && fragment.getView() != null) {
mCurrentPosition = position;
pager.measureCurrentView(fragment.getView());
}
}
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
}
FRAGMENT ONE
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/lists"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:fontFamily="sans-serif-condensed"
>
</ListView>
</FrameLayout>
Is there a way to make the above make the viewPager dynamic in height. I am grateful. Thanks

Android view Pager flip more pages on swipe

I am using ViewPager with FragmentStatePageAdapter to show a number of views where user can go through. With current implementation only one page is changed at any single swipe. Instead I want to flip through multiple views based on user swipe. If swipe is long/fast i need to flip through multiple views and vice versa.
here is my current code
public class MyAdapter extends FragmentStatePagerAdapter
{
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return 10;
}
#Override
public Fragment getItem(int position) {
return ItemFragment.init(position);
}
}
PageContainer class
public class PagerContainer extends FrameLayout implements ViewPager.OnPageChangeListener {
private ViewPager mPager;
boolean mNeedsRedraw = false;
public PagerContainer(Context context) {
super(context);
init();
}
public PagerContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagerContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
//Disable clipping of children so non-selected pages are visible
setClipChildren(false);
//Child clipping doesn't work with hardware acceleration in Android 3.x/4.x
//You need to set this value here if using hardware acceleration in an
// application targeted at these releases.
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
#Override
protected void onFinishInflate() {
try {
mPager = (ViewPager) getChildAt(0);
mPager.setOnPageChangeListener(this);
} catch (Exception e) {
throw new IllegalStateException("The root child of PagerContainer must be a ViewPager");
}
}
public ViewPager getViewPager() {
return mPager;
}
private Point mCenter = new Point();
private Point mInitialTouch = new Point();
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCenter.x = w / 2;
mCenter.y = h / 2;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
//We capture any touches not already handled by the ViewPager
// to implement scrolling from a touch outside the pager bounds.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialTouch.x = (int)ev.getX();
mInitialTouch.y = (int)ev.getY();
default:
ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y - mInitialTouch.y);
break;
}
return mPager.dispatchTouchEvent(ev);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Force the container to redraw on scrolling.
//Without this the outer pages render initially and then stay static
if (mNeedsRedraw) invalidate();
}
#Override
public void onPageSelected(int position) { }
#Override
public void onPageScrollStateChanged(int state) {
mNeedsRedraw = (state != ViewPager.SCROLL_STATE_IDLE);
}
}
How can I do this in android?
Thanks
You can change the view by calling:
ViewPager.setCurrentItem(int index)
ViewPager.setCurrentItem(int index, bool animation)
You must handle the sliding commands yourself, but on a certain slide you cloud call setCurrentItem of the ViewPager. The setCurrentItem method also allows you to enable or disable animations.

Custom ViewPager rendering issue on certain devices

I have developed a kind of rolling mechanism for choosing staff in the application. It's Custom View Pager that allows to present more then one item on screen at each time (3 in my case) and surrounded with shadow from both sides.
Here is how it should look and works like this on devices like the Nexus 5, Nexus 4, Galaxy S3:
But on some devices like (Sony Xperia, and different kinds of Motorola) the rendering looks bad, here is the result:
Regarding the code I refereed to this blog post by #Commonsware:
http://commonsware.com/blog/2012/08/20/multiple-view-viewpager-options.html
And the third option there which code you could find here.
Here is my relevant code:
PagerContainer:
public class PagerContainer extends FrameLayout implements ViewPager.OnPageChangeListener {
private ViewPager mPager;
boolean mNeedsRedraw = false;
public PagerContainer(Context context) {
super(context);
init();
}
public PagerContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagerContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
//Disable clipping of children so non-selected pages are visible
setClipChildren(false);
//Child clipping doesn't work with hardware acceleration in Android 3.x/4.x
//You need to set this value here if using hardware acceleration in an
// application targeted at these releases.
if (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT < 19)
{
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
#Override
protected void onFinishInflate() {
try {
mPager = (ViewPager) getChildAt(0);
mPager.setOnPageChangeListener(this);
} catch (Exception e) {
throw new IllegalStateException("The root child of PagerContainer must be a ViewPager");
}
}
public ViewPager getViewPager() {
return mPager;
}
private Point mCenter = new Point();
private Point mInitialTouch = new Point();
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCenter.x = w / 2;
mCenter.y = h / 2;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
//We capture any touches not already handled by the ViewPager
// to implement scrolling from a touch outside the pager bounds.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialTouch.x = (int)ev.getX();
mInitialTouch.y = (int)ev.getY();
default:
ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y - mInitialTouch.y);
break;
}
return mPager.dispatchTouchEvent(ev);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Force the container to redraw on scrolling.
//Without this the outer pages render initially and then stay static
if (mNeedsRedraw) invalidate();
}
#Override
public void onPageSelected(int position) {
invalidate();
}
#Override
public void onPageScrollStateChanged(int state) {
mNeedsRedraw = (state != ViewPager.SCROLL_STATE_IDLE);
}
}
Init part:
//Size View Pager:
//========================================
pagerSize = mContainerSize.getViewPager();
adapter = new MySizePagerAdapter();
pagerSize.setAdapter(adapter);
//Necessary or the pager will only have one extra page to show make this at least however many pages you can see
pagerSize.setOffscreenPageLimit(adapter.getCount());
//A little space between pages
pagerSize.setPageMargin(15);
//If hardware acceleration is enabled, you should also remove clipping on the pager for its children.
pagerSize.setClipChildren(false);
More research brought me to understand that this problem has something to do with the Hardware acceleration or the lack of it in some devices. But disabling it via code didn't helped me either.
I would try setting the layerType of the ViewPager and it's children to software render, instead of the parent frame layout.
You also might want to check out this blog post: http://udinic.wordpress.com/2013/09/16/viewpager-and-hardware-acceleration/
I have ended up using another implementation of a ViewPager that gave me the same result but the rendering problem was no where to be seen there, this is the code:
private class MyTypePagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView view = new TextView(getActivity());
view.setText(mTempBeverageList.get(position).getName().toUpperCase());
if (!wasTypeChanged && (!isLocaleHebrew && position == 1))
{
view.setTypeface(null, Typeface.BOLD);
view.setTextSize(19);
}
else
{
view.setTextSize(16);
}
view.setSingleLine();
view.setGravity(Gravity.CENTER);
view.setTextColor(getResources().getColor(R.color.cups_black));
view.setBackgroundColor(getResources().getColor(R.color.cups_cyan));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
return mTempBeverageList.size();
}
#Override
public float getPageWidth(int position) {
return (0.33333f);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}
And the initialization part:
pagerType= (ViewPager) view.findViewById(R.id.pagerType);
pagerType.setAdapter(new MyTypePagerAdapter());
pagerType.setOffscreenPageLimit(6);

How to do Horizontal scroll view with images scroll in two directions

I am trying to show horizontal scroll view with images to scroll in two directions.Previously for this i used Gallery View but galleryview is deprected ,i am using horizontal scroll view instead of gallery view but horizontal scroll view is different with gallery view.
Now i have to do two implementation
1) Scrolling in two directions continuously.
2) Center lock feature as same as gallery.
My screen looks like
you can use viewpager,
try this code and modify it as your need .
note : this not my code already found it on the net belong to:
( Dave Smith,#devunwired Date: 8/17/12 PagerActivity).
MainActivity:
public class MainActivity extends Activity{
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
// Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
// A little space between pages
pager.setPageMargin(15);}
// Nothing special about this adapter, just throwing up colored views for
// demo
private class MyPagerAdapter extends PagerAdapter{
#Override
public Object instantiateItem(ViewGroup container, int position){
TextView view = new TextView(MainActivity.this);
view.setText("Item " + position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50,
position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((View) object);}
#Override
public int getCount(){
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return (view == object);
}}}
PagerContainer:
public class PagerContainer extends FrameLayout implements
ViewPager.OnPageChangeListener {
private ViewPager mPager;
boolean mNeedsRedraw = false;
public PagerContainer(Context context) {
super(context);
init();
}
public PagerContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagerContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setClipChildren(false);
}
#Override
protected void onFinishInflate() {
try {
mPager = (ViewPager) getChildAt(0);
mPager.setOnPageChangeListener(this);
} catch (Exception e) {
throw new IllegalStateException("The root child of PagerContainer must be a
ViewPager");
}
}
public ViewPager getViewPager() {
return mPager;
}
private Point mCenter = new Point();
private Point mInitialTouch = new Point();
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCenter.x = w / 2;
mCenter.y = h / 2;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
//We capture any touches not already handled by the ViewPager
// to implement scrolling from a touch outside the pager bounds.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialTouch.x = (int)ev.getX();
mInitialTouch.y = (int)ev.getY();
default:
ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y -
mInitialTouch.y);
break;
}
return mPager.dispatchTouchEvent(ev);
}
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
//Force the container to redraw on scrolling.
//Without this the outer pages render initially and then stay static
if (mNeedsRedraw) invalidate();
}
public void onPageSelected(int position) { }
public void onPageScrollStateChanged(int state) {
mNeedsRedraw = (state != ViewPager.SCROLL_STATE_IDLE);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.testviewpager.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#CCC" >
<android.support.v4.view.ViewPager
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal" />
</com.example.testviewpager.PagerContainer>
</RelativeLayout>
hope help you.

Categories

Resources