在活动之间转换时,是否有一种简单而通用的方法来制作视图动画?一些只需要源视图和目标视图的函数,而无需编写任何特定于每个转换的代码。
答案 0 :(得分:0)
经过一些研究,我发现了一种通用且非常简单的方法来使用这些函数为转换设置动画:
private static final String VIEW_TRANSITION_PREFIX = "view_transition_";
public static void startActivityAnimatingViews(@NonNull final Activity activity, @NonNull final Intent intent, View... views) {
Log.d(TAG, "startActivityAnimatingViews() called with: activity = [" + activity + "], intent = [" + intent + "], views = [" + Arrays.deepToString(views) + "]");
if (views != null) {
final List<Pair<View, String>> pairs = new ArrayList<>();
for (int i = 0; i < views.length; i++) {
final View view = views[i];
final String transitionName = getTransitionNameForView(i);
view.setTransitionName(transitionName);
Pair<View, String> pair = Pair.create(view, transitionName);
pairs.add(pair);
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
//noinspection unchecked
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, pairs.toArray(new Pair[pairs.size()]));
activity.startActivity(intent, options.toBundle());
}
});
}else{
activity.startActivity(intent);
}
}
public static void onCreateActivityAnimatingViews(View... views) {
Log.d(TAG, "onCreateActivityAnimatingViews() called with: views = [" + Arrays.deepToString(views) + "]");
if (views != null) {
for (int i = 0; i < views.length; i++) {
views[i].setTransitionName(getTransitionNameForView(i));
}
}
}
@NonNull
private static String getTransitionNameForView(int index) {
return VIEW_TRANSITION_PREFIX + index;
}
要使用这些功能,您需要在想要开始新活动时调用startActivityAnimatingViews
并将其传递给您想要设置动画的当前活动中的视图。然后,在第二个活动的onCreate
中调用onCreateActivityAnimatingViews
,其中视图的目标按完全相同的顺序。
为了简化,下面是一个如何将2个视图从一个活动设置为另一个活动的示例:
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UiUtils.startActivityAnimatingViews(FirstActivity.this, new Intent(FirstActivity.this, SecondActivity.class), FirstActivity.this.findViewById(R.id.first_view1), FirstActivity.this.findViewById(R.id.first_view2));
}
});
}
}
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
UiUtils.onCreateActivityAnimatingViews(findViewById(R.id.second_view1), findViewById(R.id.second_view2));
}
}
请注意,intent
上的某些标记(例如Intent.FLAG_ACTIVITY_NEW_TASK
或Intent.FLAG_ACTIVITY_CLEAR_TASK
)可能会阻止动画生效。