先說下思路
1.如何讓小球不重疊分佈?
2.小球上下移動這個可以具體看原文作者分析
本文主要分析第一點
剛開始想法是,每次隨機生成一個x,y位置,但是這保證不了小球重疊的問題。
然後受到原文作者啓發,其實我們可以固定前面6個小球的位置,讓它們處於屏幕中心,然後剩餘的4個小球再隨機的從我們定義好的位置中獲取。
這樣就能保證10個小球既不會重疊,也不會偏離屏幕中心太遠。
private List<Float> xCanChooseList = Arrays.asList(
0.35f, 0.55f, 0.32f, 0.52f, 0.72f, 0.78f, 0.15f, 0.63f, 0.20f,
0.30f, 0.47f, 0.21f, 0.76f, 0.65f, 0.38f);
private List<Float> yCanChooseList = Arrays.asList(
0.36f, 0.45f, 0.50f, 0.28f, 0.33f, 0.50f, 0.40f, 0.63f, 0.62f,
0.75f, 0.57f, 0.20f, 0.70f, 0.17f, 0.21f);
這些是固定好的位置,不會重疊,前面6個都處於屏幕中心,剩下的則處於屏幕上下方,這樣能保證用戶每次進來不會都一樣。
private void setViewLocation(View view, int i) {
int randomInt = 0;
if (i >= 6) {
randomInt = mRandom.nextInt(xCurrentList.size());
}
float x = xCurrentList.get(randomInt) * width;
view.setX(x);
float y = yCurrentList.get(randomInt) * height;
view.setY(y);
LogUtils.e("randomInt=" + randomInt + "設置的x位置是" + xCurrentList.get(randomInt) + "y軸位置是" + yCurrentList.get(randomInt));
view.setTag(R.string.string_origin_location, (float) y);
view.setTag(R.string.string_origin_direction, mRandom.nextBoolean());
view.setTag(R.string.string_origin_spe, randomSpeed.get(mRandom.nextInt(randomSpeed.size())));
xCurrentList.remove(randomInt);
yCurrentList.remove(randomInt);
}
設置小球的位置,設置完之後,需要立馬刪除。
public interface OnStopAnimateListener {
void onBallDisappearAnimListener(String number);
void onExitAnimateListener();
}
添加了兩個動畫執行完成的方法,第一個是某一個小球執行完動畫的回調,第二個是用戶退出整個Activity進行的回調。
剩下具體思路可以看代碼。