我正在尝试创建一个简单的泡泡弹出应用程序,泡泡从屏幕底部漂浮到顶部。我希望用户能够轻敲这些气泡,并让它发出声音。我已经将声音整合到我的应用程序中,并设置了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();
}
}发布于 2019-01-23 09:43:59
你不应该使用TranslateAnimation,它是一种旧的视图动画方式(可能应该被弃用)。这种类型的动画实际上不会移动视图,而只是视图的绘图,这就是为什么单击气泡的当前可见位置不起作用的原因。
相反,您可以使用API14中引入的动画接口。更多详细信息请参阅:https://developer.android.com/guide/topics/graphics/prop-animation https://developer.android.com/training/animation/reposition-view
动画的简化版本可以这样编写:
img.animate().translationY(-deviceHeight).setDuration(4000).start()发布于 2019-01-23 10:50:05
正如前面的回答所说,您使用的是value animator,它只对图形的坐标值进行动画处理。您应该使用ObjectAnimation,它的所有属性都随视图一起移动。对于您的案例播放流行音乐开始时,您可以使用
img.animate().translationY(-deviceHeight).setDuration(4000).withStartAction(new Runnable() {
@Override
public void run() {
sound.playPopSound();
}
});https://stackoverflow.com/questions/54317380
复制相似问题