Search code examples
androidandroid-viewpagercenter

Align the child views in center of the ViewPager android


I need to set the child view as center of the ViewPager and also I would like to show some part of the next and previous views to the current view sides(like current screen below 1). But currently the current view is starting at left side of the ViewPager(like expected screen below 2). How can I achieve that?

Here is my code..

MyViewPagerAdapter

public class MyViewPagerAdapter extends PagerAdapter {
    private Activity mActivity;
    private int mPageCount;
    public MyViewPagerAdapter(Activity activity,int pageCount) {
        mActivity = activity;
        mPageCount = pageCount;
    }

    @Override
    public int getCount() {
        return mPageCount;
    }

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        return (view ==(View)obj);
    }

    @Override
    public Object instantiateItem(ViewGroup container,final int position) {
        ViewGroup viewGroup = (ViewGroup)mActivity.getLayoutInflater().inflate(
                R.layout.item_view, null);

        viewGroup.setBackgroundColor(randomColor());

        TextView textView = (TextView)viewGroup.findViewById(R.id.textView1);
        textView.setText("Page: "+(position+1));
        Button button = (Button) viewGroup.findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(mActivity, "Hey, Its clicked!!! at page "+(position+1), Toast.LENGTH_LONG).show();
            }
        });
        container.addView(viewGroup);
        return viewGroup;
    }

    Random rnd = new Random();
    private int randomColor(){
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        //must be overridden else throws exception as not overridden.
        Log.d("Tag", collection.getChildCount()+"");
        collection.removeView((View) view);
    }

    @Override
    public float getPageWidth(int position) {
        return 0.8f;
    }
}

MainActivity

public class MainActivity extends Activity {
    private ViewPager viewPager;
    LinearLayout linearLayout;
    private int ID = 100; 

    private final int count = 8;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        linearLayout  = (LinearLayout) findViewById(R.id.indicator_layout);
        generateIndicators(count);


        MyViewPagerAdapter adapter = new MyViewPagerAdapter(this, count);
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {
            int oldPosition = 0;
            @Override
            public void onPageSelected(int position) {
                //this changes the old position's view state image
                ((TextView)linearLayout.getChildAt(oldPosition)).setText("");
                oldPosition = position;


                //this changes the current position's view state image
                ((TextView)linearLayout.getChildAt(position)).setText((position+1)+"");

            }
            //this method will be called repeatedly upto another item comes as front one(active one)
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {


            }
            //this will be called as per scroll state
            @Override
            public void onPageScrollStateChanged(int arg0) {


            }
        });

        viewPager.setOffscreenPageLimit(4);

    }

    private void generateIndicators(int count) {
        /// Converts 14 dip into its equivalent px
        int padd = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, getResources().getDisplayMetrics());

        for(int i=0;i<count;i++){
            TextView textView = new TextView(this);
            textView.setId(ID+i);
            final int currentItem = i;
            textView.setBackgroundResource(R.drawable.white_cell);
            textView.setPadding(padd,padd,padd,padd);
            /// Converts 14 dip into its equivalent px
            int size = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
            textView.setTextSize(size);
            textView.setGravity(Gravity.CENTER);
            /// Converts 14 dip into its equivalent px
            int px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, getResources().getDisplayMetrics());

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(px, px);
            linearLayout.addView(textView,params);
        }

        ((TextView)linearLayout.getChildAt(0)).setText("1");

    }





}

activity_main.xml

<RelativeLayout 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"
    tools:context=".MainActivity" >



   <android.support.v4.view.ViewPager
       android:id="@+id/viewPager"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:layout_alignParentLeft="true"
       android:layout_alignParentTop="true" >
   </android.support.v4.view.ViewPager>


   <LinearLayout
       android:id="@+id/indicator_layout"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentBottom="true"
       android:layout_centerHorizontal="true"
       android:layout_marginBottom="19dp" >
   </LinearLayout>

</RelativeLayout>

item_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="match_parent"
    android:id="@+id/root_view"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="click me" />

</LinearLayout>

Current screen Current screen

expected screen expected screen


Solution

  • Finally, I have added my solution for this question in GitHub. I have done some pretty tricks to get the workaround solution. You can get the project from the below link(Actually I have planned to create a blog with the explanation , but I dint have that much time to do).

    Here is the link(https://github.com/noundla/Sunny_Projects/tree/master/CenterLockViewPager)

    You have to copy the files from com.noundla.centerviewpagersample.comps package to your project. And you can see the usage of that Viewpager in MainActivity class.

    Please let me know if anyone has problems with this.