下面列出了怎么用android.animation.StateListAnimator的API类实例代码及写法,或者点击链接到github查看源代码。
private static void setViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) {
StateListAnimator stateListAnimator = viewNodeInfo.getStateListAnimator();
final int stateListAnimatorRes = viewNodeInfo.getStateListAnimatorRes();
if (stateListAnimator == null && stateListAnimatorRes == 0) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
throw new IllegalStateException(
"MountState has a ViewNodeInfo with stateListAnimator, "
+ "however the current Android version doesn't support stateListAnimator on Views");
}
if (stateListAnimator == null) {
stateListAnimator =
AnimatorInflater.loadStateListAnimator(view.getContext(), stateListAnimatorRes);
}
view.setStateListAnimator(stateListAnimator);
}
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
setCardViewToFlat(card);
if (!Preferences.get(mContext).isShadowEnabled()) {
card.setCardElevation(0f);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StateListAnimator stateListAnimator = AnimatorInflater
.loadStateListAnimator(mContext, R.animator.card_lift_long);
card.setStateListAnimator(stateListAnimator);
}
card.setOnClickListener(this);
card.setOnLongClickListener(this);
favorite.setOnClickListener(this);
}
/**
* Creates and sets a {@link StateListAnimator} with a custom elevation value
*/
@SuppressLint("PrivateResource")
static void setDefaultAppBarLayoutStateListAnimator(final View view, final float targetElevation) {
final StateListAnimator sla = new StateListAnimator();
// Enabled, collapsible and collapsed == elevated
sla.addState(new int[]{android.R.attr.enabled, R.attr.state_collapsible, R.attr.state_collapsed},
ObjectAnimator.ofFloat(view, "elevation", targetElevation));
// Enabled and collapsible, but not collapsed != elevated
sla.addState(new int[]{android.R.attr.enabled, R.attr.state_collapsible, -R.attr.state_collapsed},
ObjectAnimator.ofFloat(view, "elevation", 0f));
// Enabled but not collapsible == elevated
sla.addState(new int[]{android.R.attr.enabled, -R.attr.state_collapsible},
ObjectAnimator.ofFloat(view, "elevation", targetElevation));
// Default, none elevated state
sla.addState(new int[0], ObjectAnimator.ofFloat(view, "elevation", 0));
view.setStateListAnimator(sla);
}
static void setStateListAnimatorFromAttrs(
@NonNull View view, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
final Context context = view.getContext();
final TypedArray a =
ThemeEnforcement.obtainStyledAttributes(
context, attrs, STATE_LIST_ANIM_ATTRS, defStyleAttr, defStyleRes);
try {
if (a.hasValue(0)) {
StateListAnimator sla =
AnimatorInflater.loadStateListAnimator(context, a.getResourceId(0, 0));
view.setStateListAnimator(sla);
}
} finally {
a.recycle();
}
}
/** Creates and sets a {@link StateListAnimator} with a custom elevation value */
static void setDefaultAppBarLayoutStateListAnimator(
@NonNull final View view, final float elevation) {
final int dur = view.getResources().getInteger(R.integer.app_bar_elevation_anim_duration);
final StateListAnimator sla = new StateListAnimator();
// Enabled and liftable, but not lifted means not elevated
sla.addState(
new int[] {android.R.attr.enabled, R.attr.state_liftable, -R.attr.state_lifted},
ObjectAnimator.ofFloat(view, "elevation", 0f).setDuration(dur));
// Default enabled state
sla.addState(
new int[] {android.R.attr.enabled},
ObjectAnimator.ofFloat(view, "elevation", elevation).setDuration(dur));
// Disabled state
sla.addState(new int[0], ObjectAnimator.ofFloat(view, "elevation", 0).setDuration(0));
view.setStateListAnimator(sla);
}
@RequiresApi(api = VERSION_CODES.LOLLIPOP)
public static StateListBuilder<Animator, StateListAnimator> animatorBuilder() {
return new StateListBuilder<Animator, StateListAnimator>() {
@Override
public StateListAnimator build() {
StateListAnimator drawable = new StateListAnimator();
int[][] states = getStates();
Animator[] values = getValues(new Animator[this.values.size()]);
for (int i = 0; i < states.length; i++) {
drawable.addState(states[i], values[i]);
}
return drawable;
}
};
}
@Test
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void testLayoutOutputsWithStateListAnimator() {
final StateListAnimator stateListAnimator = new StateListAnimator();
final Component component =
new InlineLayoutSpec() {
@Override
protected Component onCreateLayout(final ComponentContext c) {
return create(c)
.child(
create(c)
.child(SimpleMountSpecTester.create(c))
.stateListAnimator(stateListAnimator))
.build();
}
};
final LayoutState layoutState =
calculateLayoutState(
mBaseContext, component, -1, makeSizeSpec(100, EXACTLY), makeSizeSpec(100, EXACTLY));
assertThat(layoutState.getMountableOutputCount()).isEqualTo(3);
assertThat(getLayoutOutput(layoutState.getMountableOutputAt(1)).getComponent())
.isExactlyInstanceOf(HostComponent.class);
assertThat(
getLayoutOutput(layoutState.getMountableOutputAt(1))
.getViewNodeInfo()
.getStateListAnimator())
.isSameAs(stateListAnimator);
assertThat(getLayoutOutput(layoutState.getMountableOutputAt(2)).getComponent())
.isExactlyInstanceOf(SimpleMountSpecTester.class);
}
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mContext.getResources().getInteger(R.integer.categories_column_count) == 1) {
if (card.getLayoutParams() instanceof GridLayoutManager.LayoutParams) {
GridLayoutManager.LayoutParams params =
(GridLayoutManager.LayoutParams) card.getLayoutParams();
params.leftMargin = 0;
params.rightMargin = 0;
params.topMargin = 0;
params.bottomMargin = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
params.setMarginEnd(0);
}
}
} else {
setCardViewToFlat(card);
}
if (!Preferences.get(mContext).isShadowEnabled()) {
card.setCardElevation(0f);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StateListAnimator stateListAnimator = AnimatorInflater
.loadStateListAnimator(mContext, R.animator.card_lift_long);
card.setStateListAnimator(stateListAnimator);
}
card.setOnClickListener(this);
}
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StateListAnimator stateListAnimator = AnimatorInflater
.loadStateListAnimator(mContext, R.animator.card_lift_long);
card.setStateListAnimator(stateListAnimator);
}
card.setOnClickListener(this);
}
static void setStateListAnimatorFromAttrs(View view, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
final Context context = view.getContext();
final TypedArray a = context.obtainStyledAttributes(attrs, STATE_LIST_ANIM_ATTRS,
defStyleAttr, defStyleRes);
try {
if (a.hasValue(0)) {
StateListAnimator sla = AnimatorInflater.loadStateListAnimator(context, a.getResourceId(0, 0));
view.setStateListAnimator(sla);
}
} finally {
a.recycle();
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void setupRaiflat(View view) {
StateListAnimator stateListAnimator
= AnimatorInflater.loadStateListAnimator(view.getContext(),
R.drawable.raiflatbutton_statelistanimator);
view.setStateListAnimator(stateListAnimator);
}
ViewHolder(View itemView) {
super(itemView);
String viewStyle = mContext.getResources().getString(
R.string.wallpaper_grid_preview_style);
Point ratio = ViewHelper.getWallpaperViewRatio(viewStyle);
image = itemView.findViewById(R.id.image);
image.setRatio(ratio.x, ratio.y);
card = itemView.findViewById(R.id.card);
if (CandyBarApplication.getConfiguration().getWallpapersGrid() == CandyBarApplication.GridStyle.FLAT) {
if (card.getLayoutParams() instanceof GridLayoutManager.LayoutParams) {
card.setRadius(0f);
card.setUseCompatPadding(false);
int margin = mContext.getResources().getDimensionPixelSize(R.dimen.card_margin);
GridLayoutManager.LayoutParams params = (GridLayoutManager.LayoutParams) card.getLayoutParams();
params.setMargins(0, 0, margin, margin);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
params.setMarginEnd(margin);
}
}
}
if (!Preferences.get(mContext).isCardShadowEnabled()) {
card.setCardElevation(0);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StateListAnimator stateListAnimator = AnimatorInflater
.loadStateListAnimator(mContext, R.animator.card_lift);
card.setStateListAnimator(stateListAnimator);
}
if (mIsShowName) {
name = itemView.findViewById(R.id.name);
author = itemView.findViewById(R.id.author);
}
card.setOnClickListener(this);
card.setOnLongClickListener(this);
}
ConfigurationBoundResourceCache<StateListAnimator> getStateListAnimatorCache() {
return mStateListAnimatorCache;
}
private void setStateListAnimator() {
StateListAnimator stateListAnimator = AnimatorInflater.loadStateListAnimator(this, R.animator.anim_view_state_change_2);
findViewById(R.id.view_puppet2).setStateListAnimator(stateListAnimator);
}
@Nullable
@Override
public StateListAnimator getStateListAnimator() {
return null;
}
@Nullable
StateListAnimator getStateListAnimator();
@Override
public @Nullable StateListAnimator getStateListAnimator() {
return mStateListAnimator;
}
@Nullable
StateListAnimator getStateListAnimator() {
return mStateListAnimator;
}
void setStateListAnimator(StateListAnimator stateListAnimator) {
mStateListAnimator = stateListAnimator;
}
private void initSearchBar() {
Drawable drawable = ConfigurationHelper.getNavigationIcon(getActivity(),
WallpaperBoardApplication.getConfig().getNavigationIcon());
int color = ColorHelper.getAttributeColor(getActivity(), R.attr.search_bar_icon);
if (drawable != null) {
mNavigation.setImageDrawable(DrawableHelper.getTintedDrawable(drawable, color));
}
mNavigation.setOnClickListener(view -> {
if (getActivity() instanceof WallpaperBoardActivity) {
((WallpaperBoardActivity) getActivity()).openDrawer();
}
});
ImageView searchIcon = getActivity().findViewById(R.id.search);
if (searchIcon != null) {
searchIcon.setImageDrawable(DrawableHelper.getTintedDrawable(
getActivity(), R.drawable.ic_toolbar_search, color));
}
TextView searchBarTitle = getActivity().findViewById(R.id.search_bar_title);
if (searchBarTitle != null) {
if (WallpaperBoardApplication.getConfig().getAppLogoColor() != -1) {
searchBarTitle.setTextColor(WallpaperBoardApplication.getConfig().getAppLogoColor());
} else {
searchBarTitle.setTextColor(ColorHelper.setColorAlpha(color, 0.7f));
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (mSearchBar.getLayoutParams() instanceof CoordinatorLayout.LayoutParams) {
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) mSearchBar.getLayoutParams();
params.setMargins(params.leftMargin,
params.topMargin + WindowHelper.getStatusBarHeight(getActivity()),
params.leftMargin,
params.bottomMargin);
}
StateListAnimator stateListAnimator = AnimatorInflater
.loadStateListAnimator(getActivity(), R.animator.card_lift);
mSearchBar.setStateListAnimator(stateListAnimator);
}
mSearchBar.setOnClickListener(view -> {
Intent intent = new Intent(getActivity(), WallpaperBoardBrowserActivity.class);
intent.putExtra(Extras.EXTRA_FRAGMENT_ID, Extras.ID_WALLPAPER_SEARCH);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
});
mMenuSort.setImageDrawable(DrawableHelper.getTintedDrawable(
getActivity(), R.drawable.ic_toolbar_sort, color));
mMenuSort.setOnClickListener(view -> {
Popup.Builder(getActivity())
.to(mMenuSort)
.list(PopupItem.getSortItems(getActivity(), true))
.callback((popup, position) -> {
Preferences.get(getActivity())
.setSortBy(popup.getItems().get(position).getType());
refreshWallpapers();
popup.dismiss();
})
.show();
});
}
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mContext.getResources().getInteger(R.integer.latest_wallpapers_column_count) == 1) {
if (card.getLayoutParams() instanceof StaggeredGridLayoutManager.LayoutParams) {
StaggeredGridLayoutManager.LayoutParams params =
(StaggeredGridLayoutManager.LayoutParams) card.getLayoutParams();
params.leftMargin = 0;
params.rightMargin = 0;
params.topMargin = 0;
params.bottomMargin = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
params.setMarginEnd(0);
}
}
} else {
setCardViewToFlat(card);
}
if (!Preferences.get(mContext).isShadowEnabled()) {
card.setCardElevation(0f);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StateListAnimator stateListAnimator = AnimatorInflater
.loadStateListAnimator(mContext, R.animator.card_lift_long);
card.setStateListAnimator(stateListAnimator);
}
if (mContext.getResources().getBoolean(R.bool.enable_wallpaper_download)) {
download.setImageDrawable(DrawableHelper.getTintedDrawable(
mContext, R.drawable.ic_toolbar_download, Color.WHITE));
download.setOnClickListener(this);
}
apply.setImageDrawable(DrawableHelper.getTintedDrawable(
mContext, R.drawable.ic_toolbar_apply_options, Color.WHITE));
card.setOnClickListener(this);
favorite.setOnClickListener(this);
apply.setOnClickListener(this);
}
ViewHolder(View itemView) {
super(itemView);
String viewStyle = mContext.getResources().getString(
R.string.wallpaper_grid_preview_style);
Point ratio = ViewHelper.getWallpaperViewRatio(viewStyle);
image = itemView.findViewById(R.id.image);
image.setRatio(ratio.x, ratio.y);
card = itemView.findViewById(R.id.card);
if (CandyBarApplication.getConfiguration().getWallpapersGrid() == CandyBarApplication.GridStyle.FLAT) {
if (card.getLayoutParams() instanceof GridLayoutManager.LayoutParams) {
card.setRadius(0f);
card.setUseCompatPadding(false);
int margin = mContext.getResources().getDimensionPixelSize(R.dimen.card_margin);
GridLayoutManager.LayoutParams params = (GridLayoutManager.LayoutParams) card.getLayoutParams();
params.setMargins(0, 0, margin, margin);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
params.setMarginEnd(margin);
}
}
}
if (!Preferences.get(mContext).isCardShadowEnabled()) {
card.setCardElevation(0);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StateListAnimator stateListAnimator = AnimatorInflater
.loadStateListAnimator(mContext, R.animator.card_lift);
card.setStateListAnimator(stateListAnimator);
}
if (mIsShowName) {
name = itemView.findViewById(R.id.name);
author = itemView.findViewById(R.id.author);
}
card.setOnClickListener(this);
card.setOnLongClickListener(this);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setupStateListAnimator() {
mFlatStateListAnimator = new StateListAnimator();
ObjectAnimator pressed = ObjectAnimator.ofFloat(this, "elevation", 0)
.setDuration(mView.getContext().getResources()
.getInteger(android.R.integer.config_shortAnimTime));
ObjectAnimator notPressed = ObjectAnimator.ofFloat(this, "elevation", mView.getElevation()
+ mView.getTranslationZ()).setDuration(mView.getContext().getResources()
.getInteger(android.R.integer.config_shortAnimTime));
notPressed.setStartDelay(100);
mFlatStateListAnimator.addState(new int[]{android.R.attr.state_pressed,
android.R.attr.state_enabled}, pressed);
mFlatStateListAnimator.addState(new int[]{android.R.attr.state_enabled}, notPressed);
mFlatStateListAnimator.addState(new int[]{},
ObjectAnimator.ofFloat(this, "elevation", 0).setDuration(0));
mView.setStateListAnimator(mFlatStateListAnimator);
}
private void setStateListAnimator() {
StateListAnimator stateListAnimator = AnimatorInflater.loadStateListAnimator(this, R.animator.anim_view_state_change_2);
findViewById(R.id.view_puppet2).setStateListAnimator(stateListAnimator);
}
@Override
void onElevationsChanged(
final float elevation,
final float hoveredFocusedTranslationZ,
final float pressedTranslationZ) {
if (Build.VERSION.SDK_INT == VERSION_CODES.LOLLIPOP) {
// Animations produce NPE in version 21. Bluntly set the values instead in
// #onDrawableStateChanged (matching the logic in the animations below).
view.refreshDrawableState();
} else {
final StateListAnimator stateListAnimator = new StateListAnimator();
// Animate elevation and translationZ to our values when pressed, focused, and hovered
stateListAnimator.addState(
PRESSED_ENABLED_STATE_SET, createElevationAnimator(elevation, pressedTranslationZ));
stateListAnimator.addState(
HOVERED_FOCUSED_ENABLED_STATE_SET,
createElevationAnimator(elevation, hoveredFocusedTranslationZ));
stateListAnimator.addState(
FOCUSED_ENABLED_STATE_SET,
createElevationAnimator(elevation, hoveredFocusedTranslationZ));
stateListAnimator.addState(
HOVERED_ENABLED_STATE_SET,
createElevationAnimator(elevation, hoveredFocusedTranslationZ));
// Animate translationZ to 0 if not pressed, focused, or hovered
AnimatorSet set = new AnimatorSet();
List<Animator> animators = new ArrayList<>();
animators.add(ObjectAnimator.ofFloat(view, "elevation", elevation).setDuration(0));
if (Build.VERSION.SDK_INT >= 22 && Build.VERSION.SDK_INT <= 24) {
// This is a no-op animation which exists here only for introducing the duration
// because setting the delay (on the next animation) via "setDelay" or "after"
// can trigger a NPE between android versions 22 and 24 (due to a framework
// bug). The issue has been fixed in version 25.
animators.add(
ObjectAnimator.ofFloat(view, View.TRANSLATION_Z, view.getTranslationZ())
.setDuration(ELEVATION_ANIM_DELAY));
}
animators.add(
ObjectAnimator.ofFloat(view, View.TRANSLATION_Z, 0f)
.setDuration(ELEVATION_ANIM_DURATION));
set.playSequentially(animators.toArray(new Animator[0]));
set.setInterpolator(ELEVATION_ANIM_INTERPOLATOR);
stateListAnimator.addState(ENABLED_STATE_SET, set);
// Animate everything to 0 when disabled
stateListAnimator.addState(EMPTY_STATE_SET, createElevationAnimator(0f, 0f));
view.setStateListAnimator(stateListAnimator);
}
if (shouldAddPadding()) {
updatePadding();
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
int animationType = intent.getIntExtra("animation_type", 1);
String message = intent.getStringExtra("message");
this.mActionPage = new ActionPage(this);
long displayDurationMs;
if (animationType == 3) {
this.setContentView(layout.error_layout);
TextView animatedDrawable = (TextView) this.findViewById(id.message);
animatedDrawable.setText(message);
displayDurationMs = 1666L;
} else {
this.mActionPage.setColor(0);
this.mActionPage.setStateListAnimator(new StateListAnimator());
this.mActionPage.setImageScaleMode(ActionPage.SCALE_MODE_CENTER);
this.setContentView(this.mActionPage);
if (message != null) {
this.mActionPage.setText(message);
}
Drawable animatedDrawable1;
switch (animationType) {
case 1:
animatedDrawable1 = this.getResources().getDrawable(drawable.generic_confirmation_animation);
displayDurationMs = 1666L;
break;
case 2:
animatedDrawable1 = this.getResources().getDrawable(drawable.open_on_phone_animation);
displayDurationMs = 1666L;
break;
default:
throw new IllegalArgumentException("Unknown type of animation: " + animationType);
}
this.mActionPage.setImageDrawable(animatedDrawable1);
final ActionLabel label = this.mActionPage.getLabel();
long fadeDuration = label.animate().getDuration();
((Animatable) animatedDrawable1).start();
label.setAlpha(0.0F);
label.animate().alpha(1.0F).setStartDelay(50L).withEndAction(new Runnable() {
public void run() {
ConfirmationActivity.this.finish();
ConfirmationActivity.this.overridePendingTransition(0, android.R.anim.fade_out);
}
});
}
this.mActionPage.setKeepScreenOn(true);
}
@Override
public void setStateListAnimator(View view, StateListAnimator stateListAnimator) {
// do nothing
}
@Override
public void setStateListAnimator(View view, StateListAnimator stateListAnimator) {
view.setStateListAnimator(stateListAnimator);
}
/**
* Used by AnimatorInflater.
*
* @hide
*/
public ConfigurationBoundResourceCache<StateListAnimator> getStateListAnimatorCache() {
return mResourcesImpl.getStateListAnimatorCache();
}
/**
* Attaches the provided StateListAnimator to this View.
* <p>
* Any previously attached StateListAnimator will be detached.
*
* @param stateListAnimator The StateListAnimator to update the view
* @see android.animation.StateListAnimator
*/
public static void setStateListAnimator(View view, StateListAnimator stateListAnimator) {
IMPL.setStateListAnimator(view, stateListAnimator);
}