0

I am making a project in android studio.I am trying to move background image by Thread on running the app but when i am running the app it gives a message 'unfortunately stopped' . How can I move background image by Thread or anything using android studio ? Anyone please help me ?

//Xml:
<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/bg2"
    android:scaleType="fitXY"
    android:id="@+id/image_id"
    />

//java:
image=(ImageView)findViewById(R.id.image_id);  // image is an ImageView type object
Thread an=new Thread(){
        @Override
        public void run() {
            super.run();
            for(;x<=200;)
            {
                x++;
                image.setX(x);
                image.setY(0);

                System.out.println("Value of x: "+x);


                try
                {
                    sleep(1000);

                }catch(Exception e)
                {
                    System.out.println("Exception: "+e);
                }
            }
        }
    };an.start();
razu
  • 120
  • 1
  • 8

2 Answers2

1

You can use TranslateAnimation in your thread, Checkout here and here for more information

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

    TranslateAnimation animation = new TranslateAnimation(0.0f, 400.0f,
            0.0f, 0.0f);          //  new TranslateAnimation(xFrom,xTo, yFrom,yTo)
    animation.setDuration(5000);  // animation duration 
    animation.setRepeatCount(5);  // animation repeat count
    animation.setRepeatMode(2);   // repeat animation (left to right, right to left )
    //animation.setFillAfter(true);      

    img_animation.startAnimation(animation);  // start animation 
Community
  • 1
  • 1
Hana Bzh
  • 2,212
  • 3
  • 18
  • 38
0

First of all, please always post the logs. You can usually see the reason for the crash in there.

This being said, I would assume the reason for your crash it that you try to modify the UI in a non-ui-thread. You can never do that! Here is a SO question with some good explanations. Or here is some more from the android docs.

Community
  • 1
  • 1
SimonSays
  • 10,867
  • 7
  • 44
  • 59