效果图:
使用:
1、传入布局id数组。
mViewPager.setLayout(getSupportFragmentManager(),
new int[]{R.layout.activity_test,R.layout.activity_kotlin,R.layout.activity_user_info});
2、xml文件中,为需要移动的控件配置属性
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:translationXIn="0.12"
app:translationYIn="0.82"
app:translationYOut="0.82"
app:translationXOut="0.12" />
这里的实现主要是通过拦截view的创建,来一一识别控件中的属性,从而不需要再像以往,需要手动一个个findViewById,而且写出的效果不具备复用性。
关于拦截view的创建,可以前面这篇,通过AppCompateActivity,学习View的拦截
关于实现
自定义的ViewPager,主要是在addOnPageChangeListener的监听滑动,这里获取到在xml文件中设置的值,通过setTranslationX和setTranslationY的值来实现滑动的视差移动效果。
public class ParallaxViewPager extends ViewPager {
//布局数组
private int[] mLayouts;
private List<ParallaxFragment> mFragments=new ArrayList<>();
public ParallaxViewPager(Context context) {
this(context,null);
}
public ParallaxViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setLayout(FragmentManager fm,int[] layouts) {
mFragments.clear();
mLayouts = layouts;
for (int layoutId : layouts) {
ParallaxFragment fragment=new ParallaxFragment();
Bundle bundle=new Bundle();
bundle.putInt(ParallaxFragment.LAYOUT_ID_KEY,layoutId);
fragment.setArguments(bundle);
mFragments.add(fragment);
}
setAdapter(new ParallaxPagerAdapter(fm));
//监听
addOnPageChangeListener(new SimpleOnPageChangeListener(){
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
// 左out 右 in
ParallaxFragment outFragment = mFragments.get(position);
List<View> parallaxViews = outFragment.getParallaxViews();
for (View parallaxView : parallaxViews) {
ParallaxTag tag = (ParallaxTag) parallaxView.getTag(R.id.parallax_tag);
parallaxView.setTranslationX((-positionOffsetPixels)*tag.translationXOut);
parallaxView.setTranslationY((-positionOffsetPixels)*tag.translationYOut);
}
try {
ParallaxFragment inFragment = mFragments.get(position+1);
parallaxViews = inFragment.getParallaxViews();
for (View parallaxView : parallaxViews) {
ParallaxTag tag = (ParallaxTag) parallaxView.getTag(R.id.parallax_tag);
parallaxView.setTranslationX((getMeasuredWidth()-positionOffsetPixels)*tag.translationXIn);
parallaxView.setTranslationY((getMeasuredWidth()-positionOffsetPixels)*tag.translationYIn);
}
}catch (Exception e){}
}
});
}
private class ParallaxPagerAdapter extends FragmentPagerAdapter{
public ParallaxPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
}
}
重点是在在ParallaxFragment中,对Xml中的属性进行解析,当然首先是要拦截View的创建,通过设置Factory,在InflatLayout中的createView之前,交由我们来做。
public class ParallaxFragment extends Fragment implements LayoutInflater.Factory2 {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
int layouId=getArguments().getInt(LAYOUT_ID_KEY);
//克隆 inflater
inflater = inflater.cloneInContext(getContext());
LayoutInflaterCompat.setFactory2(inflater,this);
return inflater.inflate(layouId,container,false);
}
//两个实现方法
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attributeSet) {
//创建View
View view=createView(parent,name,context,attributeSet);
if(view!=null){
//解析view的属性
analysisAttrs(view,context,attributeSet);
}
return view;
}
//两个实现方法
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
return onCreateView(null, name, context, attrs);
}
}
这里参考的是系统的源码,代码在AppCompatDelegateImplV9中,不同版本可能不一样,也有可能在AppCompatDelegateImplV7
完整的代码如下
public class ParallaxFragment extends Fragment implements LayoutInflater.Factory2 {
public static final String LAYOUT_ID_KEY="layout_id_key";
private ParallaxCompatViewInflater mCompatViewInflater;
private static final boolean IS_PRE_LOLLIPOP = Build.VERSION.SDK_INT < 21;
private int [] mAttrSets=new int[]{
R.attr.translationXIn,
R.attr.translationXOut,
R.attr.translationYIn,
R.attr.translationYOut,
};
private List<View> mParallaxViews=new ArrayList<>();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
int layouId=getArguments().getInt(LAYOUT_ID_KEY);
//解析View的属性
inflater = inflater.cloneInContext(getContext());
LayoutInflaterCompat.setFactory2(inflater,this);
return inflater.inflate(layouId,container,false);
}
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attributeSet) {
//创建View
View view=createView(parent,name,context,attributeSet);
if(view!=null){
//解析view的属性
analysisAttrs(view,context,attributeSet);
}
return view;
}
/**
* 解析View的属性
* @param view
* @param context
* @param attributeSet
*/
private void analysisAttrs(View view, Context context, AttributeSet attributeSet) {
TypedArray array = context.obtainStyledAttributes(attributeSet, mAttrSets);
if(array!=null&&array.getIndexCount()!=0){
int indexCount = array.getIndexCount();
ParallaxTag tag = new ParallaxTag();
for(int i=0;i<indexCount;i++){
int attr = array.getIndex(i);
switch (attr){
case 0:
tag.translationXIn = array.getFloat(attr, 0f);
break;
case 1:
tag.translationXOut=array.getFloat(attr, 0f);
break;
case 2:
tag.translationYIn=array.getFloat(attr, 0f);
break;
case 3:
tag.translationYOut=array.getFloat(attr, 0f);
break;
}
}
view.setTag(R.id.parallax_tag,tag);
mParallaxViews.add(view);
}
array.recycle();
}
public List<View> getParallaxViews(){
return mParallaxViews;
}
@SuppressLint("RestrictedApi")
private View createView(View parent, String name, Context context, AttributeSet attributeSet) {
if (mCompatViewInflater == null) {
mCompatViewInflater = new ParallaxCompatViewInflater();
}
boolean inheritContext = false;
if (IS_PRE_LOLLIPOP) {
inheritContext = (attributeSet instanceof XmlPullParser)
// If we have a XmlPullParser, we can detect where we are in the layout
? ((XmlPullParser) attributeSet).getDepth() > 1
// Otherwise we have to use the old heuristic
: shouldInheritContext((ViewParent) parent);
}
return mCompatViewInflater.createView(parent, name, context, attributeSet, inheritContext,
IS_PRE_LOLLIPOP, /* Only read android:theme pre-L (L+ handles this anyway) */
true, /* Read read app:theme as a fallback at all times for legacy reasons */
VectorEnabledTintResources.shouldBeUsed() /* Only tint wrap the context if enabled */
);
}
private boolean shouldInheritContext(ViewParent parent) {
if (parent == null) {
// The initial parent is null so just return false
return false;
}
final View windowDecor = getActivity().getWindow().getDecorView();
while (true) {
if (parent == null) {
// Bingo. We've hit a view which has a null parent before being terminated from
// the loop. This is (most probably) because it's the root view in an inflation
// call, therefore we should inherit. This works as the inflated layout is only
// added to the hierarchy at the end of the inflate() call.
return true;
} else if (parent == windowDecor || !(parent instanceof View)
|| ViewCompat.isAttachedToWindow((View) parent)) {
// We have either hit the window's decor view, a parent which isn't a View
// (i.e. ViewRootImpl), or an attached view, so we know that the original parent
// is currently added to the view hierarchy. This means that it has not be
// inflated in the current inflate() call and we should not inherit the context.
return false;
}
parent = parent.getParent();
}
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
return onCreateView(null, name, context, attrs);
}
}
这里还有一份代码,是copy系统的源码,就是动态更改TextView,ImageView等基础控件的那个,源码为AppCompatViewInflater。
@SuppressLint("RestrictedApi")
public class ParallaxCompatViewInflater {
private static final Class<?>[] sConstructorSignature = new Class[]{
Context.class, AttributeSet.class};
private static final int[] sOnClickAttrs = new int[]{android.R.attr.onClick};
private static final String[] sClassPrefixList = {
"android.widget.",
"android.view.",
"android.webkit."
};
private static final String LOG_TAG = "AppCompatViewInflater";
private static final Map<String, Constructor<? extends View>> sConstructorMap
= new ArrayMap<>();
private final Object[] mConstructorArgs = new Object[2];
public final View createView(View parent, final String name, @NonNull Context context,
@NonNull AttributeSet attrs, boolean inheritContext,
boolean readAndroidTheme, boolean readAppTheme, boolean wrapContext) {
final Context originalContext = context;
// We can emulate Lollipop's android:theme attribute propagating down the view hierarchy
// by using the parent's context
if (inheritContext && parent != null) {
context = parent.getContext();
}
if (readAndroidTheme || readAppTheme) {
// We then apply the theme on the context, if specified
context = themifyContext(context, attrs, readAndroidTheme, readAppTheme);
}
if (wrapContext) {
context = TintContextWrapper.wrap(context);
}
View view = null;
// We need to 'inject' our tint aware Views in place of the standard framework versions
switch (name) {
case "TextView":
view = new AppCompatTextView(context, attrs);
break;
case "ImageView":
view = new AppCompatImageView(context, attrs);
break;
case "Button":
view = new AppCompatButton(context, attrs);
break;
case "EditText":
view = new AppCompatEditText(context, attrs);
break;
case "Spinner":
view = new AppCompatSpinner(context, attrs);
break;
case "ImageButton":
view = new AppCompatImageButton(context, attrs);
break;
case "CheckBox":
view = new AppCompatCheckBox(context, attrs);
break;
case "RadioButton":
view = new AppCompatRadioButton(context, attrs);
break;
case "CheckedTextView":
view = new AppCompatCheckedTextView(context, attrs);
break;
case "AutoCompleteTextView":
view = new AppCompatAutoCompleteTextView(context, attrs);
break;
case "MultiAutoCompleteTextView":
view = new AppCompatMultiAutoCompleteTextView(context, attrs);
break;
case "RatingBar":
view = new AppCompatRatingBar(context, attrs);
break;
case "SeekBar":
view = new AppCompatSeekBar(context, attrs);
break;
}
if (view == null && originalContext != context) {
// If the original context does not equal our themed context, then we need to manually
// inflate it using the name so that android:theme takes effect.
view = createViewFromTag(context, name, attrs);
}
if (view != null) {
// If we have created a view, check its android:onClick
checkOnClickListener(view, attrs);
}
return view;
}
private View createViewFromTag(Context context, String name, AttributeSet attrs) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
try {
mConstructorArgs[0] = context;
mConstructorArgs[1] = attrs;
if (-1 == name.indexOf('.')) {
for (int i = 0; i < sClassPrefixList.length; i++) {
final View view = createView(context, name, sClassPrefixList[i]);
if (view != null) {
return view;
}
}
return null;
} else {
return createView(context, name, null);
}
} catch (Exception e) {
// We do not want to catch these, lets return null and let the actual LayoutInflater
// try
return null;
} finally {
// Don't retain references on context.
mConstructorArgs[0] = null;
mConstructorArgs[1] = null;
}
}
/**
* android:onClick doesn't handle views with a ContextWrapper context. This method
* backports new framework functionality to traverse the Context wrappers to find a
* suitable target.
*/
private void checkOnClickListener(View view, AttributeSet attrs) {
final Context context = view.getContext();
if (!(context instanceof ContextWrapper) ||
(Build.VERSION.SDK_INT >= 15 && !ViewCompat.hasOnClickListeners(view))) {
// Skip our compat functionality if: the Context isn't a ContextWrapper, or
// the view doesn't have an OnClickListener (we can only rely on this on API 15+ so
// always use our compat code on older devices)
return;
}
final TypedArray a = context.obtainStyledAttributes(attrs, sOnClickAttrs);
final String handlerName = a.getString(0);
if (handlerName != null) {
view.setOnClickListener(new DeclaredOnClickListener(view, handlerName));
}
a.recycle();
}
private View createView(Context context, String name, String prefix)
throws ClassNotFoundException, InflateException {
Constructor<? extends View> constructor = sConstructorMap.get(name);
try {
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
Class<? extends View> clazz = context.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
constructor = clazz.getConstructor(sConstructorSignature);
sConstructorMap.put(name, constructor);
}
constructor.setAccessible(true);
return constructor.newInstance(mConstructorArgs);
} catch (Exception e) {
// We do not want to catch these, lets return null and let the actual LayoutInflater
// try
return null;
}
}
/**
* Allows us to emulate the {@code android:theme} attribute for devices before L.
*/
private static Context themifyContext(Context context, AttributeSet attrs,
boolean useAndroidTheme, boolean useAppTheme) {
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.View, 0, 0);
int themeId = 0;
if (useAndroidTheme) {
// First try reading android:theme if enabled
themeId = a.getResourceId(R.styleable.View_android_theme, 0);
}
if (useAppTheme && themeId == 0) {
// ...if that didn't work, try reading app:theme (for legacy reasons) if enabled
themeId = a.getResourceId(R.styleable.View_theme, 0);
if (themeId != 0) {
Log.i(LOG_TAG, "app:theme is now deprecated. "
+ "Please move to using android:theme instead.");
}
}
a.recycle();
if (themeId != 0 && (!(context instanceof ContextThemeWrapper)
|| ((ContextThemeWrapper) context).getThemeResId() != themeId)) {
// If the context isn't a ContextThemeWrapper, or it is but does not have
// the same theme as we need, wrap it in a new wrapper
context = new ContextThemeWrapper(context, themeId);
}
return context;
}
/**
* An implementation of OnClickListener that attempts to lazily load a
* named click handling method from a parent or ancestor context.
*/
private static class DeclaredOnClickListener implements View.OnClickListener {
private final View mHostView;
private final String mMethodName;
private Method mResolvedMethod;
private Context mResolvedContext;
public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
mHostView = hostView;
mMethodName = methodName;
}
@Override
public void onClick(@NonNull View v) {
if (mResolvedMethod == null) {
resolveMethod(mHostView.getContext(), mMethodName);
}
try {
mResolvedMethod.invoke(mResolvedContext, v);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Could not execute non-public method for android:onClick", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(
"Could not execute method for android:onClick", e);
}
}
@NonNull
private void resolveMethod(@Nullable Context context, @NonNull String name) {
while (context != null) {
try {
if (!context.isRestricted()) {
final Method method = context.getClass().getMethod(mMethodName, View.class);
if (method != null) {
mResolvedMethod = method;
mResolvedContext = context;
return;
}
}
} catch (NoSuchMethodException e) {
// Failed to find method, keep searching up the hierarchy.
}
if (context instanceof ContextWrapper) {
context = ((ContextWrapper) context).getBaseContext();
} else {
// Can't search up the hierarchy, null out and fail.
context = null;
}
}
final int id = mHostView.getId();
final String idText = id == View.NO_ID ? "" : " with id '"
+ mHostView.getContext().getResources().getResourceEntryName(id) + "'";
throw new IllegalStateException("Could not find method " + mMethodName
+ "(View) in a parent or ancestor Context for android:onClick "
+ "attribute defined on view " + mHostView.getClass() + idText);
}
}
}