Анимация Drawable + Android + Запуск и остановка анимации

1

Я создаю приложение, которое реализует анимацию, когда определенная переменная истинна, когда я запускаю действие, а переменная истинна, анимация работает, но если я изменю переменную, а затем верну ее обратно к истинной переменной, анимация не будет работать. Есть ли у кого-нибудь идеи относительно того, почему?

Объявлять переменные

// Load the ImageView that will host the animation and
         // set its background to our AnimationDrawable XML resource.
         chargeStatus = (ImageView)findViewById(R.id.chargeStatus);
        chargeStatus.setBackgroundResource(R.drawable.chargeon);

         // Get the background, which has been compiled to an AnimationDrawable object.
         chargeAnimation = (AnimationDrawable) chargeStatus.getBackground();   

Запускает поток в начале приложения

 /////When Application Starts
@Override
public void onStart() 
{
    super.onStart();

    Thread cThread = new Thread(new serverThread()); //Starts the thread that initiates     communications
    cThread.start();

Тема, которая устанавливает значение

public class serverThread implements Runnable 
{
    //public boolean connected = false; //connection
    public void run() //runs the thread
    {

        try 
        {
            functions.connectToServer(serverIp); //connects to server
            connected = true;

            while (connected) 
            {
                try 
                {
                    connectStatus.setImageResource(R.drawable.blue_car);
                    functions.getStreams(); //establish stream connections
                    functions. updateStatus(); //updates the status of the server
                    changeButtonImage(); //sets initial state for charge button



                    try
                    {
                        Thread.sleep(2500);
                    }
                          catch ( InterruptedException interruptedException ) 
                          {
                             functions.displayMessage( "\nThread exception" );
                          } // end catch

                }
                    catch (IOException e) 
                    {
                        Log.e("Client","Trouble Getting Streams",e);


                    }



            }//end while
        }//end try
            catch (Exception e)
            {
                Log.e("Client", "Error Connecting", e);
                connected = false;
                connectStatus.setImageResource(R.drawable.red_car);

            }
    }; //end run
}; //end serverThread     

Функция кнопки изменения

public void changeButtonImage(){
    runOnUiThread(new Runnable(){


        public void run() {


            if (functions.chargeStatNumber != 0) 
            {
                // Start the charge animation 
                 chargeAnimation.start();
                //set the Charge on off button to stop
                chargeOnOff.setImageResource(R.drawable.charge_off);

            }
            else 
            {
                // stop the charge animation if running
                 chargeAnimation.stop();
                //set charge on off button to on
                chargeOnOff.setImageResource(R.drawable.charge_on);
                //set the charging symbol to off
                chargeStatus.setImageResource(R.drawable.not_charging);
            }
        }});
}

Заранее спасибо за вашу помощь.

Теги:
multithreading
animation

1 ответ

0

Ниже код может помочь вам. Укажите имя для изображений incrementaly (image1, image2, image3...).

public class DemoAnimation extends Activity {
    private boolean reverseOrder = false;
    private int imageIndex = 0;
    AnimationThread animThread;
    ImageView imgdone;
    public void onCreate(Bundle instance) {
        super.onCreate(instance);
        setContentView(R.layout.main);
        imgdone=(ImageView)findViewById(R.id.image);
        if (animThread == null) {
            animThread = new AnimationThread();
            animThread.start();
    }
    }
    Handler handler = new Handler() {
        public void handleMessage(Message message) {
            try {
                imgdone.setBackgroundResource(R.drawable.image
                        + message.arg1);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private class AnimationThread extends Thread {
        boolean _startAnimation = true;

        public void run() {

            while (_startAnimation) {

                Message message = new Message();
                if (!reverseOrder) {

                    if (imageIndex >= 5)
                        reverseOrder = true;

                    message.arg1 = imageIndex;
                    if (imageIndex < 5)
                        imageIndex++;
                    else if (imageIndex == 5)
                        imageIndex--;

                } else {

                    if (imageIndex <= 0)
                        reverseOrder = false;
                    message.arg1 = imageIndex;
                    if (imageIndex > 0)
                        imageIndex--;
                    else if (imageIndex == 0)
                        imageIndex++;

                }
                handler.sendMessage(message);

                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        }
    }

}

//чтобы остановить поток

if (animThread != null)
    animThread._startAnimation = false;
  • 0
    удалил, извините это был тупой вопрос.
  • 0
    Я искал и пытался выяснить это, но как вы сделали это, где вы можете изменить номера изображений, и просто оставить первую часть названия пустой? imgdone.setBackgroundResource (R.drawable.image + message.arg1); Я получаю сообщение об ошибке, что piture не существует, и .arg1 выдает ошибку, хотя я импортировал методы сообщений Android.
Показать ещё 6 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню