如何实现从片段到另一活动的共享元素过渡

时间:2018-06-22 12:24:43

标签: android android-fragments android-activity android-transitions shared-element-transition

我需要2个活动,其中1个活动有片段。我希望缩放缩放动画(共享元素过渡)从Activity1中的片段开始,并在Activity2中结束。

代码如下:

活动1:SourceGridFragmentActivity.java

 @Override
  public void gridItemOnFragmentClicked(ImageView sharedImage) {
    Intent intent = new Intent(this, DestinationActivity.class);
    intent.putExtra(Constants.KEY_INTENT_TRANSITION_NAME,
        ViewCompat.getTransitionName(sharedImage));

    ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(
        this,
        sharedImage,
        ViewCompat.getTransitionName(sharedImage));

    startActivity(intent, options.toBundle());
  }

活动1中的片段: FragmentClassForGrid.java

private void initializeGridView() {
    gridBinding.gridView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
    gridBinding.gridView.setAdapter(new GridAdapter(getActivity(), this));
  }

  @Override
  public void onGridItemClick(ImageView sharedImageView) {
    activityView.gridItemOnFragmentClicked(sharedImageView);
  }

回收站适配器: GridAdapter.java

@Override
  public void onBindViewHolder(
          ViewHolder holder, int position) {
    ViewCompat.setTransitionName(holder.imageView, Constants.TRANSITION_NAME_IMAGE_TO_ACTIVITY);
    holder.imageView.setOnClickListener(v ->
        gridAcitvityView.onGridItemClick(holder.imageView));
  }

需要动画结束的活动2: DestinationActivity.java

@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    destBinding = DataBindingUtil.setContentView(this, R.layout.activity_destination);
    supportPostponeEnterTransition();
    initializeZoomView();
  }

  private void initializeZoomView() {
    Bundle extras = getIntent().getExtras();
    destBinding.destinationImageView
        .setTransitionName(extras.getString(Constants.KEY_INTENT_TRANSITION_NAME));
    supportStartPostponedEnterTransition();
    destBinding.destinationImageView
        .setImageDrawable(getResources().getDrawable(R.drawable.model));
  }

0 个答案:

没有答案