Android ViewPager+View.setTranslationX实现可滑动的指示器效果

jopen 9年前

对于需求较为严格一些,应该让ViewPager滑动时,那个指示器也应该滑动才符合逻辑,因此如上代码改造为如下代码

public class AnimActivity extends BaseActivity {     private View vline;     /**    * 指示器偏移宽度    */   private int offsetWidth = 0;      private ViewPager mViewPager;      /**    * viewPager宽度    */   private int screenWith = 0;   /**    * viewPager高度    */   private int screeHeight = 0;      private int[] drawableResIds = {R.drawable.mm_1,R.drawable.mm_2};      @Override   protected void onCreate(Bundle saveInstance) {    super.onCreate(saveInstance);    setContentView(R.layout.anim_layout);    vline = findViewById(R.id.line);    mViewPager = (ViewPager) findViewById(R.id.anim_view_pager);      screenWith = getWindow().getWindowManager().getDefaultDisplay().getWidth();    screeHeight = getWindow().getWindowManager().getDefaultDisplay().getHeight()-dip2px(this, 45);    //这里之所以是45,请查看布局文件,其中ViewPager以上的节点的高度总和为45        LayoutParams lp = vline.getLayoutParams();    offsetWidth = lp.width = screenWith / 2;    vline.setLayoutParams(lp);    vline.setTag("0");        mViewPager.setOnPageChangeListener(pageChangedListener);    mViewPager.setAdapter(new ViewPagerAdapter());       }      private  OnPageChangeListener  pageChangedListener = new OnPageChangeListener() {        private boolean isAnim = false;    private int pos = 0;        @Override    public void onPageSelected(int position)     {     Log.e("ViewPager", "position===>"+position);     vline.setTranslationX(position*offsetWidth);     pos = position;    }        @Override    public void onPageScrolled(int arg0, float arg1, int arg2) {     Log.d("ViewPager", "arg0="+arg0+"  arg1="+arg1+"   arg2="+arg2);     if(isAnim && arg1!=0)     {        vline.setTranslationX(offsetWidth*arg1);     }    }        @Override    public void onPageScrollStateChanged(int arg0)     {     Log.i("ViewPager", "=====>arg0="+arg0);     if(arg0==1) //开始状态     {      isAnim  = true;     }     else if(arg0==2) //分界状态     {      isAnim = false;      vline.setTranslationX(pos*offsetWidth);     }     else if(arg0==0) //结束状态     {      vline.setTranslationX(pos*offsetWidth);     }    }       };     private class ViewPagerAdapter extends PagerAdapter   {        @Override    public int getCount() {     return drawableResIds.length;    }    @Override    public Object instantiateItem(ViewGroup container, int position)    {     ImageView imageView = (ImageView) layoutInflater.inflate(R.layout.image_display, null);     imageView.setImageBitmap(adjustBitmapSimpleSize(drawableResIds[position]));     imageView.setTag(position);     container.addView(imageView);                              return imageView;      }        @Override    public void destroyItem(ViewGroup container, int position, Object object)    {     ImageView image = (ImageView)((ViewPager) container).findViewWithTag(position);                          ((ViewPager) container).removeView(image);      }      @Override    public boolean isViewFromObject(View arg0, Object arg1)     {     return arg0==arg1;    }       }      /**    * 调整压缩采样率    * @param resId    * @return    */   private Bitmap adjustBitmapSimpleSize(int resId)   {    BitmapFactory.Options opts = new BitmapFactory.Options();    opts.inJustDecodeBounds = true;    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),resId, opts);    int visibleHeight = screeHeight;    int visibleWidth = screenWith;    if(opts.outWidth>visibleWidth ||opts.outHeight>visibleHeight)    {     float wRatio =  opts.outWidth/visibleWidth;     float hRatio =  opts.outHeight/visibleHeight;     opts.inSampleSize = (int) Math.max(wRatio, hRatio);    }    opts.inJustDecodeBounds = false;    bitmap.recycle();    return BitmapFactory.decodeResource(getResources(),resId, opts);   }      public void doSwicth(View v) {    switch (v.getId())     {     case R.id.fade_anim_left:      {      mViewPager.setCurrentItem(0,true);     }      break;     case R.id.fade_anim_right:      mViewPager.setCurrentItem(1,true);      break;         default:      break;    }   }          /**        * 根据手机的分辨率从 dp 的单位 转成为 px(像素)        */        public static int dip2px(Context context, float dpValue) {            final float scale = context.getResources().getDisplayMetrics().density;            return (int) (dpValue * scale + 0.5f);        }            /**        * 根据手机的分辨率从 px(像素) 的单位 转成为 dp        */        public static int px2dip(Context context, float pxValue) {            final float scale = context.getResources().getDisplayMetrics().density;            return (int) (pxValue / scale + 0.5f);        }    }

布局文件:anim_layout.xml

<?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:orientation="vertical" >            <LinearLayout           android:layout_width="match_parent"          android:layout_height="wrap_content"          android:orientation="horizontal"          >           <Button           android:id="@+id/fade_anim_left"           android:layout_width="match_parent"           android:layout_height="40dip"           android:layout_weight="1"           android:text="Left"            android:onClick="doSwicth"           android:background="@drawable/fade_anim"          />           <View                android:layout_width="1dip"               android:layout_height="30dip"               android:background="@color/red"               />            <Button                          android:id="@+id/fade_anim_right"           android:layout_width="match_parent"           android:layout_height="40dip"           android:text="Right"            android:layout_weight="1"           android:onClick="doSwicth"           android:background="@drawable/fade_anim"          />      </LinearLayout>            <View           android:id="@+id/line"          android:layout_width="160dip"          android:layout_height="5dip"          android:background="@color/red"          />              <android.support.v4.view.ViewPager          android:id="@+id/anim_view_pager"          android:layout_width="match_parent"          android:layout_height="match_parent"          android:scrollbars="vertical"          android:keepScreenOn="true"          >            <!-- <android.support.v4.view.PagerTabStrip                  android:id="@+id/anim_view_pager_tabsctrip"                  android:layout_width="wrap_content"                  android:layout_height="wrap_content"                  android:layout_gravity="top"/>    -->      </android.support.v4.view.ViewPager>    </LinearLayout>


image_display.xml

<?xml version="1.0" encoding="utf-8"?>  <ImageView xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="match_parent"      android:scaleType="centerCrop"      android:layout_height="match_parent" >    </ImageView>

Tab按钮渐变背景

 

<?xml version="1.0" encoding="utf-8"?>  <selector       xmlns:android="http://schemas.android.com/apk/res/android"      android:enterFadeDuration="0"      android:exitFadeDuration="300"      android:visible="true"             >      <item  android:state_pressed="false" android:state_focused="false" android:drawable="@color/white" />   <item android:state_pressed="true" android:drawable="@color/red"/>   <item android:state_focused="true" android:drawable="@color/red"/>  </selector>

运行如下:

Android ViewPager+View.setTranslationX实现可滑动的指示器效果    Android ViewPager+View.setTranslationX实现可滑动的指示器效果 

   Android ViewPager+View.setTranslationX实现可滑动的指示器效果    Android ViewPager+View.setTranslationX实现可滑动的指示器效果