我正在尝试创建一个简单的气泡弹出应用程序,气泡从屏幕底部浮动到顶部。我希望用户能够点击这些气泡并发出声音。我已经将声音合并到我的应用程序中并设置了onClickListeners()
,但是当我单击气泡图像时却没有声音。我知道这是由于调用动画方法时调整了图像位置。
我在网上找到了一些答案,但是由于我是新来的,所以对于我来说,大多数答案太复杂了。
public class MainActivity extends AppCompatActivity {
private ImageView bubble, bubble1, bubble2, bubble3, bubble4, bubble5, bubble6, bubble7, bubble8;
//Created an array that stores the images
private ImageView[] IMGS= new ImageView[9];
private SoundPlayer sound;
private int deviceHeight;
private Animation mAnimation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sound = new SoundPlayer(this);
//linked up views
bubble = findViewById(R.id.bubble);
bubble1 = findViewById(R.id.bubble1);
bubble2 = findViewById(R.id.bubble2);
bubble3 = findViewById(R.id.bubble3);
bubble4 = findViewById(R.id.bubble4);
bubble5 = findViewById(R.id.bubble5);
bubble6 = findViewById(R.id.bubble6);
bubble7 = findViewById(R.id.bubble7);
bubble8 = findViewById(R.id.bubble8);
//assigned the array to the imageviews
IMGS[0] = bubble;
IMGS[1] = bubble1;
IMGS[2] = bubble2;
IMGS[3] = bubble3;
IMGS[4] = bubble4;
IMGS[5] = bubble5;
IMGS[6] = bubble6;
IMGS[7] = bubble7;
IMGS[8] = bubble8;
getDeviceHeight();
animateBubble();
}
public void animateBubble(){
//looped thru the array of Imageviews and animated the images stored in it.
for (ImageView img : IMGS) {
mAnimation = new TranslateAnimation(0, 0, 0, -deviceHeight);
mAnimation.setDuration(4000);
mAnimation.setFillAfter(true);
bubble.setAnimation(mAnimation);
bubble.setVisibility(View.VISIBLE);
img.setAnimation(mAnimation);
img.setVisibility(View.VISIBLE);
mAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
sound.playPopSound();
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
}
public void getDeviceHeight(){
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
deviceHeight = displayMetrics.heightPixels;
}
public void playSound(View view) {
sound.playPopSound();
}
}
答案 0 :(得分:0)
您不应该使用TranslateAnimation,这是给Views设置动画的一种古老方法(可能不建议使用)。这种动画实际上不会移动视图,而只会移动视图的图形,这就是为什么单击气泡的当前可见位置将无效的原因。
您可以使用API 14中引入的动画API。更多详细信息,请参见: https://developer.android.com/guide/topics/graphics/prop-animation https://developer.android.com/training/animation/reposition-view
动画的简化版可以这样写:
img.animate().translationY(-deviceHeight).setDuration(4000).start()
答案 1 :(得分:0)
如前一个答案所述,您正在使用值动画器,该动画器仅对图形的坐标值进行动画处理。您应该使用ObjectAnimation的所有属性随视图一起移动。如果您想在播放开始时播放流行音乐,可以使用
img.animate().translationY(-deviceHeight).setDuration(4000).withStartAction(new Runnable() {
@Override
public void run() {
sound.playPopSound();
}
});