延迟for loop-android

时间:2014-07-23 07:10:36

标签: android for-loop

我是Android编程的新手,我有一个简单的问题。我有一个随机数,nr和我在同一个位置生成这个数量的ImageViews。现在,我想对每个图像应用动画,但不是在同一时间。

让我们说我希望第一张图像在第0秒开始移动,然后在第2秒开始移动图像,依此类推。

我有一个数组中的图像,imb_items []。

for(int j=0; j<nr;j++){
imb_items[j].startAnimation(translateAnim);
 ????? how can I put here the delay?
}

我尝试了很长时间才能做到这一点,但我无法通过处理程序或线程来做这件事......我想我不会理解这个概念。 如果有人帮助我理解并给我一个可以在我的具体情况下工作的示例代码,我将非常感激。

谢谢你!

public class MyActivity extends ActionBarActivity implements OnClickListener {

    private TextView mCalculatorDisplay;
    private Boolean userIsInTheMiddleOfTypingANumber = false;
    private CalculatorBrain mCalculatorBrain;
    private static final String DIGITS = "0123456789.";
    DecimalFormat df = new DecimalFormat("@###########");
    Animation anim_translate;
    public double valoare, produs, scor = 0;
    int printfirst, printsecond;
    Handler mHandler = new Handler();
    int[] idMultiple = new int[]{6, 5, 3, 4, 2};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        //Img.setVisibility(View.VISIBLE);

        //android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

        Animation translateAnim = AnimationUtils.loadAnimation(MyActivity.this, R.anim.translate);

        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int height = displaymetrics.heightPixels;
        int width = displaymetrics.widthPixels;

        int dpHeight = (int)(displaymetrics.heightPixels / displaymetrics.density );
        int dpWidth = (int)(displaymetrics.widthPixels / displaymetrics.density );
        ImageView imb1=(ImageView)findViewById(R.id.ImageView1 );



        Toast.makeText(getApplicationContext(), "Spiridusii lui Mos Craciun pregatesc jucariile pentru copii.",
                Toast.LENGTH_LONG).show();
        Toast.makeText(getApplicationContext(), "Ei au observat ca unele jucarii sunt  incomplete. Ajuta-i sa comande piesele lipsa!",
                Toast.LENGTH_LONG).show();



        Toast.makeText(getApplicationContext(), height+"inaltime"+width,
                Toast.LENGTH_LONG).show();

        Toast.makeText(getApplicationContext(), dpHeight+"inaltime"+dpWidth,
                Toast.LENGTH_LONG).show();

        RelativeLayout Layout=(RelativeLayout)findViewById(R.id.rel_banda);

        ImageView banda=(ImageView) findViewById(R.id.banda);


        mCalculatorBrain = new CalculatorBrain();
        mCalculatorDisplay = (TextView) findViewById(R.id.Raspuns_user);

        df.setMinimumFractionDigits(0);
        df.setMinimumIntegerDigits(1);
        df.setMaximumIntegerDigits(2);

        findViewById(R.id.b0).setOnClickListener(this);
        findViewById(R.id.b1).setOnClickListener(this);
        findViewById(R.id.b2).setOnClickListener(this);
        findViewById(R.id.b3).setOnClickListener(this);
        findViewById(R.id.b4).setOnClickListener(this);
        findViewById(R.id.b5).setOnClickListener(this);
        findViewById(R.id.b6).setOnClickListener(this);
        findViewById(R.id.b7).setOnClickListener(this);
        findViewById(R.id.b8).setOnClickListener(this);
        findViewById(R.id.b9).setOnClickListener(this);
        findViewById(R.id.buttonClear).setOnClickListener(this);

        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                {
                    valoare = Double.parseDouble(String.valueOf(mCalculatorDisplay.getText()));


                    genereaza_imagini();


                    check_answer();

                }
            }
        };
        mHandler.post(runnable);


        //genereaza_imagini dinamic de la una la 9 imagini de un anumit tip

    }


    //max poate fi 5 sau 9



    public void genereaza_imagini() {


        final TextView et1, et2;
        et1 = (TextView) findViewById(R.id.printfirst);
        et2 = (TextView) findViewById(R.id.printsecond);


        int nr1 = random(5);
        printsecond = random(9);
        printfirst = idMultiple[nr1 - 1];
        produs = printsecond * printfirst;
        et1.setTextSize(13);
        et2.setTextSize(13);
        et1.setText("nr piese lipsa:" + printfirst);
        et2.setText("nr jucarii:" + printsecond);

        et1.setVisibility(View.VISIBLE);
        et2.setVisibility(View.VISIBLE);

        ImageView imb1 = (ImageView) findViewById(R.id.ImageView1);
        ImageView imb2 = (ImageView) findViewById(R.id.ImageView2);
        ImageView imb3 = (ImageView) findViewById(R.id.ImageView3);
        ImageView imb4 = (ImageView) findViewById(R.id.ImageView4);

        ImageView imb5 = (ImageView) findViewById(R.id.ImageView5);
        ImageView imb6 = (ImageView) findViewById(R.id.ImageView6);
        ImageView imb7 = (ImageView) findViewById(R.id.ImageView7);
        ImageView imb8 = (ImageView) findViewById(R.id.ImageView8);
        ImageView imb9 = (ImageView) findViewById(R.id.ImageView9);
        final ImageView[] imb_items = new ImageView[]{imb1, imb2, imb3, imb4, imb5, imb6, imb7, imb8, imb9};


        for (int j = 0; j < 9; j++) {

            RelativeLayout.LayoutParams lp;
            lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);

            DisplayMetrics displaymetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
            int height = displaymetrics.heightPixels;
            int width = displaymetrics.widthPixels;

            int dpHeight = (int) (displaymetrics.heightPixels / displaymetrics.density);
            int dpWidth = (int) (displaymetrics.widthPixels / displaymetrics.density);
            lp.leftMargin = dpWidth / 2 - dpWidth / 10;

            lp.topMargin = dpHeight / 4;

            imb_items[j].setLayoutParams(lp);
            imb_items[j].getLayoutParams().height = 30;
            imb_items[j].getLayoutParams().width = 30;


            imb_items[j].setImageResource(0);
            imb_items[j].setVisibility(View.GONE);
        }

        final int i = printsecond;  // cate imagini din cele 9


        if (nr1 == 1) {
            Toast.makeText(getApplicationContext(), "Omizilor le lipsesc 6 picioare.",
                    Toast.LENGTH_SHORT).show();

            for (int j = 0; j < i; j++) {
                imb_items[j].setImageResource(R.drawable.obj1);
                imb_items[j].setVisibility(View.VISIBLE);


            }
        }

        if (nr1 == 2) {


            Toast.makeText(getApplicationContext(), "Florilor le lipsesc 5 petale. ",
                    Toast.LENGTH_SHORT).show();

            for (int j = 0; j < i; j++) {
                imb_items[j].setImageResource(R.drawable.obj2);
                imb_items[j].setVisibility(View.VISIBLE);


            }
        }


        if (nr1 == 3) {

            Toast.makeText(getApplicationContext(), "Papusilor le lipsesc 3 nasturi. ",
                    Toast.LENGTH_SHORT).show();

            for (int j = 0; j < i; j++) {
                imb_items[j].setImageResource(R.drawable.obj3);
                imb_items[j].setVisibility(View.VISIBLE);


            }
        }
        if (nr1 == 4) {

            Toast.makeText(getApplicationContext(), "Masinilor le lipsesc 4 roti. ",
                    Toast.LENGTH_SHORT).show();

            for (int j = 0; j < i; j++) {
                imb_items[j].setImageResource(R.drawable.obj4);
                imb_items[j].setVisibility(View.VISIBLE);


            }
        }
        if (nr1 == 5) {

            Toast.makeText(getApplicationContext(), "Robotilor le lipsesc 2 antene. ",
                    Toast.LENGTH_SHORT).show();

            for (int j = 0; j < i; j++) {
                imb_items[j].setImageResource(R.drawable.obj5);
                imb_items[j].setVisibility(View.VISIBLE);

            }
        }

        final Animation translateAnim = AnimationUtils.loadAnimation(MyActivity.this, R.anim.translate);

        Thread thread = new Thread() {
            public void run() {
                while (true) {
                    try {


                        for(int j=0; j<i;j++){
                            imb_items[j].startAnimation(translateAnim); ???????????????????????????????????????????

                         Thread.sleep(2000);
                        }


                    } catch (InterruptedException e) {
                        Log.v( "tag", "local Thread error");
                    }
                }
            }
        };
        thread.start();


    }



    public int random(int max) {
        Random r = new Random();
        int random = r.nextInt(max) + 1;
        return random;
    }

    public void check_answer() {

        Button b = (Button) findViewById(R.id.button);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                valoare = Double.parseDouble(String.valueOf(mCalculatorDisplay.getText()));
                verifica();

            }

        });
    }
    //functie care afiseaza la onCreate, cand apas pe buton 2: nr1, nr2, raspuns corect nr1*nr2

    public void verifica() {

        final TextView et1, et2;
        et1 = (TextView) findViewById(R.id.printfirst);
        et2 = (TextView) findViewById(R.id.printsecond);
        TextView Scor = (TextView) findViewById(R.id.Scorul);
        if (produs == valoare) {
            Toast.makeText(getApplicationContext(), "Raspunsul este corect! :)",
                    Toast.LENGTH_SHORT).show();

            Log.v("Produsul este corect=", String.valueOf(produs));

            scor = scor + 50;

            Scor.setText("Scor:" + scor);
        } else {
            Toast.makeText(getApplicationContext(), "Raspunsul este gresit! :(",
                    Toast.LENGTH_SHORT).show();

            Log.v("Produsul nu este corect=", String.valueOf(produs));
            scor = scor - 50;
            Scor.setText("Scor:" + scor);
        }


// ca sa actualizeze automat text view-ul raspuns user la 0.0

        if (userIsInTheMiddleOfTypingANumber) {

            mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
            userIsInTheMiddleOfTypingANumber = false;
        }

        mCalculatorBrain.performOperation("C");
        mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));

        genereaza_imagini();

    }


    // mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
    // }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.my, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }



    @Override
    public void onClick(View v) {

        String buttonPressed = ((Button) v).getText().toString();

        if (DIGITS.contains(buttonPressed)) {

            // digit was pressed
            if (userIsInTheMiddleOfTypingANumber) {

                if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
                    // ERROR PREVENTION
                    // Eliminate entering multiple decimals
                } else {
                    mCalculatorDisplay.append(buttonPressed);
                }

            } else {

                if (buttonPressed.equals(".")) {
                    // ERROR PREVENTION
                    // This will avoid error if only the decimal is hit before an operator, by placing a leading zero
                    // before the decimal
                    mCalculatorDisplay.setText(0 + buttonPressed);
                } else {
                    mCalculatorDisplay.setText(buttonPressed);
                }

                userIsInTheMiddleOfTypingANumber = true;
            }

        } else {
            // operation was pressed
            if (userIsInTheMiddleOfTypingANumber) {

                mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
                userIsInTheMiddleOfTypingANumber = false;
            }

            mCalculatorBrain.performOperation(buttonPressed);
            mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));

        }

    }

    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // Save variables on screen orientation change
        outState.putDouble("OPERAND", mCalculatorBrain.getResult());
        outState.putDouble("MEMORY", mCalculatorBrain.getMemory());
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // Restore variables on screen orientation change
        mCalculatorBrain.setOperand(savedInstanceState.getDouble("OPERAND"));
        mCalculatorBrain.setMemory(savedInstanceState.getDouble("MEMORY"));
        mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
    }




}


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/banda_bk"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"

    android:visibility="visible"
    tools:context=".MyActivity">

    <RelativeLayout android:layout_height="wrap_content"
        android:layout_width="wrap_content"


        android:layout_centerInParent="true"
        android:id="@+id/rel_banda">

        <ImageView

            android:id="@+id/banda"

            android:visibility="visible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/banda" />

        <ImageView

            android:id="@+id/ImageView1"
            android:layout_marginRight="92dp"
            android:layout_marginBottom="52dp"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_toLeftOf="@+id/linearLayout4"
            android:visibility="gone"/>

        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:id="@+id/ImageView2"
            android:layout_alignLeft="@+id/ImageView1"
            android:layout_alignStart="@+id/ImageView1"
            android:visibility="gone"/>

        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:id="@+id/ImageView3"
            android:layout_marginRight="41dp"
            android:layout_toLeftOf="@+id/ImageView2"
            android:visibility="gone"/>

        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:id="@+id/ImageView4"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginLeft="16dp"
            android:visibility="gone"/>

        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:id="@+id/ImageView5"
            android:layout_marginTop="25dp"
            android:layout_below="@+id/ImageView4"
            android:layout_alignLeft="@+id/ImageView4"
            android:layout_alignStart="@+id/ImageView4"
            android:visibility="gone"/>

        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:id="@+id/ImageView6"
            android:layout_alignTop="@+id/ImageView5"
            android:layout_alignLeft="@+id/ImageView3"
            android:layout_alignStart="@+id/ImageView3"
            android:layout_marginTop="14dp"
            android:visibility="gone"/>

        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:id="@+id/ImageView7"
            android:layout_alignTop="@+id/ImageView6"
            android:layout_toRightOf="@+id/ImageView6"
            android:layout_marginLeft="22dp"
            android:visibility="gone"/>

        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:id="@+id/ImageView8"
            android:layout_alignTop="@+id/ImageView7"
            android:layout_toRightOf="@+id/ImageView2"
            android:visibility="gone"/>

        <ImageView
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:id="@+id/ImageView9"
            android:layout_alignTop="@+id/ImageView8"
            android:layout_toRightOf="@+id/ImageView8"
            android:layout_marginLeft="26dp"
            android:visibility="gone"/>


    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true">

        <LinearLayout
            android:id="@+id/row1"
            android:layout_width="600dp"
            android:layout_height="wrap_content"
            android:gravity="bottom">

            <Button
                android:id="@+id/b0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight=".15"
                android:text="@string/b0"
                android:textSize="12sp" />

            <Button
                android:id="@+id/b1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight=".15"
                android:text="@string/b1"
                android:textSize="12sp"
                android:visibility="visible" />

            <Button
                android:id="@+id/b2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight=".15"
                android:text="@string/b2"
                android:textSize="12sp"
                android:visibility="visible" />

            <Button
                android:id="@+id/b3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight=".15"
                android:text="@string/b3"
                android:textSize="12sp"
                android:visibility="visible" />

            <Button
                android:id="@+id/b4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight=".15"
                android:text="@string/b4"
                android:textSize="12sp"
                android:visibility="visible" />


            <Button
                android:id="@+id/b5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight=".15"
                android:text="@string/b5"
                android:textSize="12sp"
                android:visibility="visible" />

            <Button
                android:id="@+id/b6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight=".15"
                android:text="@string/b6"
                android:textSize="12sp"
                android:visibility="visible" />

            <Button
                android:id="@+id/b7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight=".15"
                android:text="@string/b7"
                android:textSize="12sp"
                android:visibility="visible" />

            <Button
                android:id="@+id/b8"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight=".15"
                android:text="@string/b8"
                android:textSize="12sp"
                android:visibility="visible" />

            <Button
                android:id="@+id/b9"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight=".15"
                android:text="@string/b9"
                android:textSize="12sp"
                android:visibility="visible" />

            <Button
                android:id="@+id/buttonClear"
                android:layout_width="33dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:text="@string/buttonClear"
                android:textSize="12sp" />


        </LinearLayout>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/linearLayout4"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginBottom="33dp">

        <TextView
            android:id="@+id/printfirst"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0" />

        <TextView
            android:id="@+id/printsecond"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0" />

        <TextView
            android:id="@+id/Raspuns_user"
            android:layout_width="100dp"
            android:layout_weight=".15"
            android:maxLines="1"
            android:text="0"
            android:textColor="@color/textbody"
            android:textSize="15sp"
            android:layout_height="wrap_content" />


        <Button
            android:id="@+id/button"
            android:layout_width="60dp"
            android:layout_height="30dp"
            android:textSize="10sp"
            android:text="Check" />

        <TextView
            android:id="@+id/Scorul"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Scor"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/textbody"
            android:textSize="10sp" />


    </LinearLayout>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Ajutati spiridusii sa afle numarul total de piese lipsa. "
        android:id="@+id/textView"
        android:textSize="13dp"
        android:textColor="@color/textbody"

        android:layout_alignParentTop="true"  />

</RelativeLayout>

5 个答案:

答案 0 :(得分:1)

试试这个:

Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
         public void run() { 



       // YOUR CODE HERE


         } 
    }, 2000); 

其中2000是主线程中的2秒延迟/睡眠。

答案 1 :(得分:1)

你可以使用线程概念和循环你可以使用睡眠功能延迟,你可以在其中编写代码

thread = new Thread() {
        public void run() {
            while (true) {
                try {


                   YOUR FOR LOOP CODE HERE with this line "Thread.sleep(2000);"


                } catch (InterruptedException e) {
                    Log.e(TAG, "local Thread error", e);
                }
            }
        }
    };
    thread.start();

答案 2 :(得分:0)

对于创建延迟,您可以使用以下代码:

try {
    Thread.sleep(m); // m is millisecond, if m = 1000 ms then delay = 1 s
}
catch (InterruptedException e) {
   e.printStackTrace();
}

答案 3 :(得分:0)

如果我使用这个

for(int j=0; j<i;j++) {
        final int finalJ = j;
        new android.os.Handler().postDelayed(
                new Runnable() {
                    public void run() {


                        imb_items[finalJ].startAnimation(translateAnim);


                        Log.i("tag", "This'll run 5000 milliseconds later");

                    }
                },
                5000 * j
        );
    }
问题是,当第二张图像开始移动时,第一张图像会停止并消失。我希望所有的图像继续运动。

答案 4 :(得分:0)

这是最终解决方案:

for(int j=0; j<i;j++) {
   translateAnim[j].setStartOffset(5000*j);
   imb_items[j].startAnimation(translateAnim[j]);
}