译者语:在开源社区上逛久了,的确涨了新知识,不过也发现已经旧的很好的东西,没人留意,我就吧StyleAndroid上一些东西翻译出来供大家来学习(StyleAndroid貌似在国内访问比较慢,还是建议大家卖个VPN,很便宜实惠)

现在离Google发布Android 4.4 KitKat已经近两周了,他提供了新的API来供大家使用,接下来的这一系列的我们将看一下新的API中的渐变动画。

在以前的StylingAndroid(译者注:本文的作者网站)我们已经介绍了很多种动画,那么Android 4。4有什么新的API来让我们使用呢?最基本就是它提供了可以同时让多个View以同样的方式进行动画效果,貌似老版的也提供了,不过不同的是新版的API自己为我们做了很多工作,解放了大家。

下面有个示范的例子。先来看下布局文件吧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<LinearLayout
android:id="@+id/layout_1"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical"
android:padding="@dimen/margin">

<TextView
android:id="@+id/item_1a"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="@dimen/item_height"
android:background="@color/red"
android:text="Item 1a"
android:gravity="center"
android:textAppearance="@style/Text"
android:layout_margin="@dimen/margin"/>

<TextView
android:id="@+id/item_1b"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="@dimen/item_height"
android:background="@color/green"
android:text="Item 1b"
android:gravity="center"
android:textAppearance="@style/Text"
android:layout_margin="@dimen/margin"/>

</LinearLayout>

假如我们想通过点击其中的一个TextView,就有一个动画来交换这两个TextView。在以前,我们可能通过属性动画(property animator)实现—使用translateY来改变TextView在竖直方向上的位置。这个可能需要我们简单的计算已动画结束的位置来确保他们能落到正确的位置上。在动画结束时,我们需要在LinearLayout交互位置,并移出动画。

有了4.4的新API,这就简单多了。

逻辑上我们需要先交换这个TextView在LinearLayout里:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private ViewGroup mLayout1;

@Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState){
View view=inflater.inflate(R.layout.fragment_part1,
container,false);
mLayout1=(ViewGroup)view.findViewById(R.id.layout_1);
mLayout1.findViewById(R.id.item_1a)
.setOnClickListener(this);
mLayout1.findViewById(R.id.item_1b)
.setOnClickListener(this);
return view;
}

@Override
public void onClick(View v){
int selected=mLayout1.indexOfChild(v);
mLayout1.removeView(v);
mLayout1.addView(v,
selected==0?mLayout1.getChildCount():0)
}

这没什么难的啊,我们只是在父组件里先删除了一个view,然后又重新在插入一个新的位置上。为了能使他们能有动画,我们只需要加入两行代码。只需要两行!

实际上只有一行,还有一行只是在分开view以确保原来的view不会滚动。

实际上

1
2
3
4
5
6
7
@Override
public void onClick(View v) {
int selected = mLayout1.indexOfChild(v);
TransitionManager.beginDelayedTransition(mLayout1, new ChangeBounds());
mLayout1.removeView(v);
mLayout1.addView(v, selected == 0 ? mLayout1.getChildCount() : 0);
}