本文的合集已經(jīng)編著成書,高級Android開發(fā)強(qiáng)化實(shí)戰(zhàn)秕噪,歡迎各位讀友的建議和指導(dǎo)饺谬。在京東即可購買:https://item.jd.com/12385680.html
又是一個Android的動畫效果, Material提出的. Fragment切換時, 有一些元素(element)會保持不變, 如何使這些元素切換時, 賦予動畫效果呢? 需要設(shè)置addSharedElement()方法, 目前只支持api21+. 那么我們就來看一下吧.
本文源碼的GitHub下載地址
1. 準(zhǔn)備
還是從一個HelloWorld工程開始.
build.gradle
添加兩個常用庫, recyclerview和butterknife.
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.android.support:recyclerview-v7:23.1.0'
修改主題顏色
<color name="colorPrimary">#FF1493</color>
<color name="colorPrimaryDark">#FF1493</color>
去掉狀態(tài)條(status bar)
的透明顏色, 在style中, 刪除statusBarColor.
<item name="android:statusBarColor">@android:color/transparent</item>
2. 主頁面
在Activity中添加Fragment, 內(nèi)容在Fragment中添加
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 替換Fragment
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.main_cl_container, new GridFragment())
.commit();
}
}
Fragment中使用RecyclerView創(chuàng)建一個網(wǎng)格(Grid)頁面, 為Item添加點(diǎn)擊監(jiān)聽, 這個下一步再完成. Item顯示一個圖片和一行文字.
public class GridFragment extends Fragment {
private ArrayList<Pair<Integer, Integer>> mData;
@Bind(R.id.grid_rv_recycler)
RecyclerView mRvRecycler;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_grid, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initData();
mRvRecycler.setAdapter(new MyGridAdapter(mData, mListener));
mRvRecycler.setLayoutManager(new GridLayoutManager(getContext(), 2)); // 一行兩個
}
private MyViewOnClickListener mListener = new MyViewOnClickListener() {
@Override
public void onClickedView(MyGridViewHolder holder, int position) {
}
};
// 初始化數(shù)據(jù)
private void initData() {
mData = new ArrayList<>();
mData.add(Pair.create(R.string.taeyeon, R.drawable.taeyeon));
mData.add(Pair.create(R.string.jessica, R.drawable.jessica));
mData.add(Pair.create(R.string.sunny, R.drawable.sunny));
mData.add(Pair.create(R.string.tiffany, R.drawable.tiffany));
mData.add(Pair.create(R.string.yuri, R.drawable.yuri));
mData.add(Pair.create(R.string.yoona, R.drawable.yoona));
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
RecyclerView的Adapter
/**
* Fragment的網(wǎng)格適配器
* <p/>
* Created by wangchenlong on 15/11/5.
*/
public class MyGridAdapter extends RecyclerView.Adapter<MyGridViewHolder> {
private ArrayList<Pair<Integer, Integer>> mData; // 名字和圖片
private MyViewOnClickListener mListener; // 點(diǎn)擊事件
public MyGridAdapter(ArrayList<Pair<Integer, Integer>> data,
MyViewOnClickListener listener) {
mData = data;
mListener = listener;
}
@Override
public MyGridViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_item, parent, false);
return new MyGridViewHolder(view);
}
@Override
public void onBindViewHolder(final MyGridViewHolder holder, final int position) {
holder.getTextView().setText(mData.get(position).first);
holder.getImageView().setImageResource(mData.get(position).second);
// 把每個圖片視圖設(shè)置不同的Transition名稱, 防止在一個視圖內(nèi)有多個相同的名稱, 在變換的時候造成混亂
// Fragment支持多個View進(jìn)行變換, 使用適配器時, 需要加以區(qū)分
ViewCompat.setTransitionName(holder.getImageView(), String.valueOf(position) + "_image");
holder.getImageView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onClickedView(holder, position);
}
});
}
@Override
public int getItemCount() {
return mData.size();
}
}
注意
ViewCompat.setTransitionName();
, 把不同的視圖設(shè)置不同的變換名稱, 防止造成混亂, 同時支持多個視圖同時變換.
ViewHolder
/**
* 提供了Grid的ImageView
* <p/>
* Created by wangchenlong on 15/11/5.
*/
public class MyGridViewHolder extends RecyclerView.ViewHolder {
private ImageView mImageView;
private TextView mTextView;
public MyGridViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.grid_image);
mTextView = (TextView) itemView.findViewById(R.id.grid_text);
}
public ImageView getImageView() {
return mImageView;
}
public TextView getTextView() {
return mTextView;
}
}
點(diǎn)擊接口, 提供ViewHolder和點(diǎn)擊的位置position.
public interface MyViewOnClickListener {
void onClickedView(MyGridViewHolder holder, int position);
}
效果
3. 詳情頁面
主頁面跳轉(zhuǎn)之后的詳情頁面, 根據(jù)選擇的ID, 創(chuàng)建不同內(nèi)容的Fragment, 點(diǎn)擊圖片返回上一個Fragment, 和主頁面聯(lián)動執(zhí)行動畫, 動畫邏輯在主頁面的FragmentManager中添加的.
/**
* 詳情頁面
* <p/>
* Created by wangchenlong on 15/11/5.
*/
public class DetailFragment extends Fragment {
private static final String ARG_NUMBER = "arg_number";
private ArrayList<DetailData> mDetailDatas;
@Bind(R.id.detail_image)
ImageView mImage;
@Bind(R.id.detail_head)
TextView mHead;
@Bind(R.id.detail_body)
TextView mBody;
/**
* 根據(jù)選擇的number, 選擇展示的數(shù)據(jù)
*
* @param number 數(shù)字
* @return 詳情頁面
*/
public static DetailFragment newInstance(@IntRange(from = 0, to = 5) int number) {
Bundle bundle = new Bundle();
bundle.putInt(ARG_NUMBER, number);
DetailFragment detailFragment = new DetailFragment();
detailFragment.setArguments(bundle);
return detailFragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initData();
int number = getArguments().getInt(ARG_NUMBER);
mImage.setImageResource(mDetailDatas.get(number).getImage());
mHead.setText(mDetailDatas.get(number).getHead());
mBody.setText(mDetailDatas.get(number).getBody());
mImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStack();
}
});
}
// 初始化數(shù)據(jù)
private void initData() {
mDetailDatas = new ArrayList<>();
mDetailDatas.add(new DetailData(R.drawable.taeyeon, R.string.taeyeon, R.string.taeyeon_detail));
mDetailDatas.add(new DetailData(R.drawable.jessica, R.string.jessica, R.string.jessica_detail));
mDetailDatas.add(new DetailData(R.drawable.sunny, R.string.sunny, R.string.sunny_detail));
mDetailDatas.add(new DetailData(R.drawable.tiffany, R.string.tiffany, R.string.tiffany_detail));
mDetailDatas.add(new DetailData(R.drawable.yuri, R.string.yuri, R.string.yuri_detail));
mDetailDatas.add(new DetailData(R.drawable.yoona, R.string.yoona, R.string.yoona_detail));
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
// 定義類
private class DetailData {
private int mImage;
private int mHead;
private int mBody;
public DetailData(int image, int head, int body) {
mImage = image;
mHead = head;
mBody = body;
}
public int getImage() {
return mImage;
}
public int getHead() {
return mHead;
}
public int getBody() {
return mBody;
}
}
}
關(guān)鍵的資源文件, 有一條重要的屬性, android:transitionName=""
表明需要轉(zhuǎn)換對象的名稱, 在點(diǎn)擊事件中使用.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:id="@+id/detail_image"
android:layout_width="240dp"
android:layout_height="240dp"
android:scaleType="centerCrop"
android:src="@drawable/tiffany"
android:transitionName="@string/image_transition"
tools:ignore="UnusedAttribute"/>
<TextView
android:id="@+id/detail_head"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tiffany"
android:textAppearance="@style/TextAppearance.AppCompat.Headline"/>
<TextView
android:id="@+id/detail_body"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tiffany_detail"
android:textAppearance="@style/TextAppearance.AppCompat.Body2"/>
</LinearLayout>
效果
重寫GridFragment
的點(diǎn)擊事件
/**
* 點(diǎn)擊事件, 轉(zhuǎn)換元素的動畫,
* 關(guān)鍵addSharedElement(holder.getImageView(), getResources().getString(R.string.image_transition))
* 綁定ViewHolder的圖片和DetailFragment的跳轉(zhuǎn).
*/
private MyViewOnClickListener mListener = new MyViewOnClickListener() {
@Override
public void onClickedView(MyGridViewHolder holder, int position) {
DetailFragment detailFragment = DetailFragment.newInstance(position);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
detailFragment.setSharedElementEnterTransition(new DetailTransition());
setExitTransition(new Fade());
detailFragment.setEnterTransition(new Fade());
detailFragment.setSharedElementReturnTransition(new DetailTransition());
}
getActivity().getSupportFragmentManager().beginTransaction()
.addSharedElement(holder.getImageView(), getResources().getString(R.string.image_transition))
.replace(R.id.main_cl_container, detailFragment)
.addToBackStack(null)
.commit();
}
};
關(guān)鍵addSharedElement(), 確定轉(zhuǎn)換的元素View.
Fade是淡出動畫; DetailTransition是自定義動畫.
填寫動畫屬性
/**
* 轉(zhuǎn)換動畫
* Created by wangchenlong on 15/11/5.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class DetailTransition extends TransitionSet {
public DetailTransition() {
init();
}
// 允許資源文件使用
public DetailTransition(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setOrdering(ORDERING_TOGETHER);
addTransition(new ChangeBounds()).
addTransition(new ChangeTransform()).
addTransition(new ChangeImageTransform());
}
}
動畫效果, 添加屬性即可.
ChangeBounds: 視圖的位置和大小;
ChangeTransform: 視圖的比例(scale);
ChangeImageTransform: 圖像的比例;
都完成了, 當(dāng)切換Fragment時, 關(guān)聯(lián)視圖就會使用動畫進(jìn)行播放!
OK, that's all ! Enjoy it!