使用ViewPager时仅滑动一半碎片

时间:2014-01-23 12:04:17

标签: android android-viewpager

我有一个应用程序,我使用ViewPager在两个片段之间滑动。我可以完美地在两个片段之间滑动;但现在我只需要滑动片段的一半。怎么做?这是我尝试过的:

这是我的主要活动

public class MainActivity extends FragmentActivity 
{
      MyPageAdapter pageAdapter;
      Context c;
      int[] pics = {R.drawable.ic_launcher};

      @Override
      public void onCreate(Bundle savedInstanceState) 
      {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        c = MainActivity.this;
        pageAdapter = new MyPageAdapter(getSupportFragmentManager(), c, pics);
        ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
        pager.setAdapter(pageAdapter);
      }
    }

PageAdapter.java

        class MyPageAdapter extends FragmentPagerAdapter {
          Context c;
          int[] pics;
          Fragment fragment;

          public MyPageAdapter(android.support.v4.app.FragmentManager fm,  Context c, int[] pics) {
            super(fm);
            this.c =c;
            this.pics = pics;
          }

          @Override 
          public Fragment getItem(int position) {
              switch(position){
              case 0:return new MyFragment();
              case 1: return new NewFragment();
              default: return new MyFragment();
              }
          }

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

MyFragment.java

        public class MyFragment extends Fragment {
             public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
             public static final MyFragment newInstance(String message,int a)
             {
                 MyFragment f = new MyFragment();
                 return f;
             }

             @Override
             public View onCreateView(LayoutInflater inflater, ViewGroup container,
               Bundle savedInstanceState) {

               View v = inflater.inflate(R.layout.myfragment_layout, container, false);
               TextView messageTextView = (TextView)v.findViewById(R.id.textView);
               messageTextView.setText("hi");
               v.setBackgroundColor(Color.parseColor("#ff0000"));
               return v;
             }
    }

NewFragment.java

        public class NewFragment extends Fragment {
        public static final MyFragment newInstance(String message,int a)
         {
           MyFragment f = new MyFragment();
           return f;
         }

         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {
           View v = inflater.inflate(R.layout.new_fragment, container, false);
           Button b1 = (Button) v.findViewById(R.id.b1);
           v.setBackgroundColor(Color.parseColor("#0000ff"));
           return v;
         }
    }

1 个答案:

答案 0 :(得分:0)

覆盖getPageWidth的{​​{1}}方法并将其设为PagerAdapter