据我了解你的问题,你想在运行时动态缩小/长大你的矩形。这里是我的一个可能的解决方案草案:
在我的布局的XML文件,我添加了两个按钮增大和缩小,在那里我可以触发10%的增长/收缩动画:
<Button
android:text="Grow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/grow"
android:textSize="30sp" />
<Button
android:text="Skrink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/shrink"
android:layout_below="@+id/grow"
android:layout_alignLeft="@+id/grow"
android:layout_alignStart="@+id/grow"
android:layout_alignRight="@+id/grow"
android:layout_alignEnd="@+id/grow"
android:textSize="30sp" />
<ImageView
android:id="@+id/bluerect"
android:layout_height="100dp"
android:layout_width="50dp"
android:src="@drawable/bluerect"
android:layout_below="@+id/shrink1"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
在类与相应的活性,我声明以下字段:
private Button grow;
private Button shrink;
private ImageView img_animation;
private float startdim[] = {1f, 1f};
private float enddim[] = {1f, 1f};
这三个字段到所述手柄存储到两个按钮和ImageView的,和两个阵列至约尺寸将数据存储在开始和结束时的动画。
在OnCreate方法我加入下面几行:
grow = (Button) findViewById(R.id.grow);
shrink = (Button) findViewById(R.id.shrink);
img_animation = (ImageView) findViewById(R.id.bluerect);
if (grow != null) grow.setOnClickListener(this);
if (shrink != null) shrink.setOnClickListener(this);
在这里,我得到了手柄的按钮和imageview的并且设置当前类作为OnClickListener的实施者。
接下来,我已经封装你animationcode的方法makeanimation:
private void makeAnimation(boolean shrink){
if (shrink){
enddim[0] -= 0.1f;
enddim[1] -= 0.1f;
}
else{
enddim[0] += 0.1f;
enddim[1] += 0.1f;
}
ScaleAnimation fade_in = new ScaleAnimation(startdim[0], enddim[0], startdim[1], enddim[1],
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
fade_in.setDuration(1000); // animation duration in milliseconds
fade_in.setFillAfter(true); // If fillAfter is true, the transformation that this animation performed will persist when it is finished.
if (img_animation != null) {
img_animation.startAnimation(fade_in);
startdim[0] = enddim[0];
startdim[1] = enddim[1];
}
}
最后我重写OnClick方法来获得buttonclicks:
@Override
public void onClick(View v) {
if(grow == v){
makeAnimation(false);
}
if(shrink == v){
makeAnimation(true);
}
}
哪里是动画的代码? – Alex
ImageView img_animation =(ImageView)findViewById(R.id.bluerect); ScaleAnimation fade_in = new ScaleAnimation(0f,1f,0f,1f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f); fade_in.setDuration(1000); //动画持续时间(以毫秒为单位) fade_in.setFillAfter(true); //如果fillAfter为true,则此动画执行的转换在完成时将保持不变。 img_animation.startAnimation(fade_in); shrink = false; –