안 드 로 이 드 오늘 의 톱 슬라이딩 페이지 내 비게 이 션 효과 모방

최근 프로젝트 에서 미끄럼 페이지 를 사 용 했 습 니 다.즉,현재 시장 에서 인기 가 많은'오늘 의 톱기사'페이지 가 미 끄 러 지 는 것 과 비슷 합 니 다.인터넷 에서 찾 아 보 니 대부분이 ViewPager 로 이 루어 졌 습 니 다.처음에 저 는 ViewPager+ViewGroup 을 사 용 했 습 니 다.위의 제목 단 추 는 Horizontal ScrollView 를 사 용 했 습 니 다.쓰 고 나 니 효과 가 딱딱 하고 과감하게 바 뀌 었 습 니 다.효과 가 비교적 좋 은 제3자,즉 오늘 의 주 제 를 발 견 했 습 니 다:PagerSlidingTabStrip.자,다음은 PagerSlidingTabStrip 를 구체 적 으로 소개 하고 소스 코드 분석 을 진행 하 겠 습 니 다.
1.데모 의 모습 을 보 세 요.


2.PagerSlidingTabStrip 을 프로젝트 에 가 져 옵 니 다.
그리고 우리 의 레이아웃 파일 에서 설명 합 니 다.

<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:app="http://schemas.android.com/apk/res/com.hankkin.PagerSlidingTabStrip" 
 android:orientation="vertical" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 > 
 
 <com.hankkin.PagerSlidingTabStrip.view.PagerSlidingTabStrip 
 android:id="@+id/tab" 
 app:pstsShouldExpand="false" 
 app:pstsUnderlineHeight="2dp" 
 app:pstsIndicatorHeight="2dp" 
 app:pstsIndicatorColor="@android:color/holo_blue_light" 
 app:selectedTabTextColor="@android:color/holo_blue_light" 
 app:pstsDividerColor="@android:color/transparent" 
 app:pstsTabBackground="@drawable/background" 
 android:background="@android:color/white" 
 android:layout_width="match_parent" 
 android:layout_height="55dp"/> 
 
 <android.support.v4.view.ViewPager 
 android:id="@+id/pager" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent"/> 
 
</LinearLayout></span><span style="font-size:18px;"> 
</span> 
위 에 있 는 것 은 바로 우리 의 제목 슬라이딩 버튼 입 니 다.아래 의 ViewPager 는 우리 의 내용 을 저장 하 는 데 사 용 됩 니 다.
3.어댑터 만 들 기

<span style="font-size:14px;">package com.hankkin.PagerSlidingTabStrip.adapter; 
 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentPagerAdapter; 
import com.hankkin.PagerSlidingTabStrip.fragment.AndroidFragment; 
import com.hankkin.PagerSlidingTabStrip.fragment.JavaFragment; 
import com.hankkin.PagerSlidingTabStrip.fragment.ObjectCFragment; 
 
import java.util.List; 
 
public class MyAdapter extends FragmentPagerAdapter { 
 private AndroidFragment androidFragment; 
 private JavaFragment javaFragment; 
 private ObjectCFragment objectCFragment; 
 private String[] titles; 
 public MyAdapter(FragmentManager fm,String[] titles) { 
 super(fm); 
 this.titles = titles; 
 } 
 
 @Override 
 public Fragment getItem(int position) { 
 switch (position) { 
 case 0: 
 if (androidFragment == null) { 
  androidFragment = new AndroidFragment(); 
 } 
 return androidFragment; 
 case 1: 
 if (javaFragment == null) { 
  javaFragment = new JavaFragment(); 
 } 
 return javaFragment; 
 case 2: 
 if (objectCFragment == null) { 
  objectCFragment = new ObjectCFragment(); 
 } 
 return objectCFragment; 
 default: 
 return null; 
 } 
 } 
 
 @Override 
 public int getCount() { 
 return titles.length; 
 } 
 
 public String getPageTitle(int i){ 
 return titles[i]; 
 } 
 
} 
</span> 
제 가 사용 하 는 것 은 조각 Fragment 입 니 다.맨 아래 getPageTitle()은 저희 PagerSlidingTabStrip 의 방법 입 니 다.제목 을 가 져 오 는 데 사 용 됩 니 다.
이제 Pager Sliding TabStrip 과 ViewPager 그리고 저희 조각 을 초기 화 하 겠 습 니 다.

<span style="font-size:14px;"> private void initViews(){ 
 fragments = new ArrayList<>(); 
 pagerTab = (PagerSlidingTabStrip) findViewById(R.id.tab); 
 pager = (ViewPager) findViewById(R.id.pager); 
 
 for (int i=0;i<titles.length;i++){ 
 Fragment fragment = new Fragment(); 
 fragments.add(fragment); 
 } 
 
 adapter = new MyAdapter(getSupportFragmentManager(),titles); 
 pager.setAdapter(adapter); 
 pagerTab.setViewPager(pager); 
 }</span> 
Adapter 에서 조각 관리 자 를 이용 하여 우리 의 조각 과 제목 을 가 져 옵 니 다.이 안 에는 주의 가 필요 합 니 다.조각의 개수 가 적 으 면 수 동 으로 조각 을 만 들 수 있 습 니 다.오늘 처럼 특종 이 많 으 면 괜 찮 습 니 다.동적 으로 Fragment 를 만 듭 니 다.특종 의 모든 조각 에 있 는 내용 이 유사 하 다 는 것 을 볼 수 있 기 때문에 동적 으로 만 들 수도 없습니다.개별 특수 한 것 만 우리 가 특별 처리 할 수 있다.
이렇게 간단 하면 톱기사 와 같은 페이지 슬라이딩 효 과 를 실현 할 수 있 습 니 다.다음은 Pager Sliding TabStrip 의 소스 코드 를 살 펴 보 겠 습 니 다.알 아 본 후에 도 개선 할 수 있 습 니 다.
4.PagerSlidingTabStrip 소스 코드 분석
우선 중요 한 속성 몇 가 지 를 볼 게 요.

private int indicatorColor = 0xFF666666;//         
private int underlineColor = 0x1A000000;//            pstsunderlinecolor   
private int dividerColor = 0x1A000000;//        pstsdividercolor   
 
private boolean shouldExpand = false;//pstsshouldexpand     TRUE,            ,   false 
private boolean textAllCaps = true;//pststextallcaps    ,           ,   true 
 
private int scrollOffset = 52;//pstsscrolloffset            
private int indicatorHeight = 8;//     pstsindicatorheight 
private int underlineHeight = 2;//            pstsunderlineheight   
private int dividerPadding = 12;//pstsdividerpadding            
private int tabPadding = 24;//pststabpaddingleftright 、         
private int dividerWidth = 1;//         
 
private int tabTextSize = 12;//        
private int tabTextColor = 0xFF666666;//        
private int selectedTabTextColor = 0xFF666666;//         
private Typeface tabTypeface = null; 
private int tabTypefaceStyle = Typeface.NORMAL; 
 
private int lastScrollX = 0; 
 
private int tabBackgroundResId = R.drawable.background;//pststabbackground         ,     statelistdrawable 
우 리 는 이 속성의 값 을 스스로 정의 할 수 있 습 니 다.왜냐하면 기본 값 이 그다지 예 쁘 지 않 을 수 있 기 때 문 입 니 다.
1.우선 우리 의 구조 가 어떤 속성 을 초기 화 하 는 지 살 펴 보 자.

<span style="font-size:14px;">public PagerSlidingTabStrip(Context context, AttributeSet attrs, int defStyle) { 
 super(context, attrs, defStyle); 
 
 setFillViewport(true);//    view            
 setWillNotDraw(false);//     OnDraw()   
 //               
 tabsContainer = new LinearLayout(context); 
 tabsContainer.setOrientation(LinearLayout.HORIZONTAL); 
 tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 
 addView(tabsContainer); 
 
 DisplayMetrics dm = getResources().getDisplayMetrics(); 
 //         
 scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm); 
 indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm); 
 underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm); 
 dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm); 
 tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm); 
 dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm); 
 tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm); 
 
 // get system attrs (android:textSize and android:textColor) 
 
 TypedArray a = context.obtainStyledAttributes(attrs, ATTRS); 
 
 tabTextSize = a.getDimensionPixelSize(0, tabTextSize); 
 tabTextColor = a.getColor(1, tabTextColor); 
 
 a.recycle(); 
 
 // get custom attrs 
 
 a = context.obtainStyledAttributes(attrs, R.styleable.PagerSlidingTabStrip); 
 
 indicatorColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsIndicatorColor, indicatorColor); 
 
 //tab        ,              
 selectedTabTextColor=a.getColor(R.styleable.PagerSlidingTabStrip_selectedTabTextColor, indicatorColor); 
 //        
 underlineColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsUnderlineColor, underlineColor); 
 dividerColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsDividerColor, dividerColor); 
 indicatorHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsIndicatorHeight, indicatorHeight); 
 underlineHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsUnderlineHeight, underlineHeight); 
 dividerPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsDividerPadding, dividerPadding); 
 tabPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsTabPaddingLeftRight, tabPadding); 
 tabBackgroundResId = a.getResourceId(R.styleable.PagerSlidingTabStrip_pstsTabBackground, tabBackgroundResId); 
 shouldExpand = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsShouldExpand, shouldExpand); 
 scrollOffset = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsScrollOffset, scrollOffset); 
 textAllCaps = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsTextAllCaps, textAllCaps); 
 
 a.recycle(); 
 
 rectPaint = new Paint(); 
 rectPaint.setAntiAlias(true); 
 rectPaint.setStyle(Style.FILL); 
 
 dividerPaint = new Paint(); 
 dividerPaint.setAntiAlias(true); 
 dividerPaint.setStrokeWidth(dividerWidth); 
 
 defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); 
 expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f); 
 
 if (locale == null) { 
 locale = getResources().getConfiguration().locale; 
 } 
 }</span> 
이런 것들 은 기본적으로 모두 알 아 볼 수 있 는데 주로 일부 속성 을 초기 화 하 는 것 이 고 코드 에 도 해당 하 는 주석 이 있 으 므 로 일일이 소개 하지 않 겠 습 니 다.
2.ViewPager 슬라이딩 모니터 를 정의 하고 현재 pager 의 위 치 를 설정 합 니 다.

<span style="font-size:14px;">private class PageListener implements OnPageChangeListener { 
 
 @Override 
 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 
 currentPosition = position; 
 currentPositionOffset = positionOffset; 
 
 scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth())); 
 
 invalidate(); 
 
 if (delegatePageListener != null) { 
 delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels); 
 } 
 } 
 
 @Override 
 public void onPageScrollStateChanged(int state) { 
 if (state == ViewPager.SCROLL_STATE_IDLE) { 
 scrollToChild(pager.getCurrentItem(), 0); 
 } 
 
 if (delegatePageListener != null) { 
 delegatePageListener.onPageScrollStateChanged(state); 
 } 
 } 
 
 @Override 
 public void onPageSelected(int position) { 
 selectedPosition = position; 
 updateTabStyles(); 
 if (delegatePageListener != null) { 
 delegatePageListener.onPageSelected(position); 
 } 
 } 
 
 }</span> 
3.제목 스타일 을 업데이트 합 니 다.즉,현재 제목 아래로 미끄러져 제목 상 태 를 설정 합 니 다.

<span style="font-size:14px;">private void updateTabStyles() { 
 
 for (int i = 0; i < tabCount; i++) { 
 
 View v = tabsContainer.getChildAt(i); 
 
 v.setBackgroundResource(tabBackgroundResId); 
 
 if (v instanceof TextView) { 
 
 TextView tab = (TextView) v; 
 tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize); 
 tab.setTypeface(tabTypeface, tabTypefaceStyle); 
 tab.setTextColor(tabTextColor); 
 
 // setAllCaps() is only available from API 14, so the upper case is made manually if we are on a 
 // pre-ICS-build 
 if (textAllCaps) { 
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 
  tab.setAllCaps(true); 
  } else { 
  tab.setText(tab.getText().toString().toUpperCase(locale)); 
  } 
 } 
 if (i == selectedPosition) { 
  tab.setTextColor(selectedTabTextColor); 
 } 
 } 
 } 
 
 }</span> 
거의 다 르 지 않 습 니 다.자,제 가 보완 한 모습 을 보 여 드 리 겠 습 니 다.

많이 조정 하지 않 았 습 니 다.다만 스타일 을 조금 바 꾸 었 을 뿐 그 안에 비교적 디 테 일 한 것 이 소개 되 지 않 았 습 니 다.예 를 들 어 제목 의 너비 가 평균 분배 인지 분 체 글씨체 의 길 이 를 설정 하 는 지,우 리 는 shouldExpand 속성 을 수정 할 수 있 습 니 다.여러분 이 관심 이 있 는 자신 이 자세히 연구 해 보 세 요.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기