简体   繁体   中英

Changing image in imageview using Threads

I'm getting error with this code. Why huhu 123123123

Thread timer = new Thread()
{
    public void run()
    {
        try
        {
            sleep(1500);
            splash.setImgeResource(R.drawable.dilclogo);
            sleep(1500);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        finally
        {
            Intent intent = new Intent(MainActivity.this, MenuScreen.class);
            startActivity(intent);
        }
    }
};
timer.start();

This is because you can NOT access your UI/Main thread directly from any other thread. You can use below methods to access your UI thread though:

  1. Using AsyncTask
  2. Using runOnUiThread()

You can also read this article on threading in android to help you understand this concept better.

put splash.setImgeResource(R.drawable.dilclogo); line into runOnUiThread .

Thread timer = new Thread()
            {
                public void run()
                {
                    try
                    {
                        sleep(2000);
                       runOnUiThread(new Runnable() {
                        public void run() {
                             splash.setImageResource(R.drawable.billboard_image);
                        }
                    });

                        sleep(2000);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                 splash.setImageResource(R.drawable.square);
                            }
                        });
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    finally
                    {
                       System.out.println("finally");
                    }
                }
            };
            timer.start();

You can not use normal threading on android system. Give you some example on thread on android :D

---> Android Asynctask

Android Developer - Android Asynctask

You can use this for some loading effect on UI in android.

---> runOnUiThread

In your case, I suggest to use this. You can have more detail here.

Click for detail

USEAGE::

runOnUiThread(new Runnable() {

  @Override
  public void run() {
    // Do you ui update here
  }

});

You should update ui on the ui thread. Use runonUithread.

  runOnUiThread(new Runnable() {

  @Override
  public void run() {
   // set image to imageview here
   // ui should be updated on the ui thread.
   // you cannot update ui from a background thread  
  }
 });

But i would suggest you to use a handler.

public class Splash extends Activity {

//stopping splash screen starting home activity.
private static final int STOPSPLASH = 0;
//time duration in millisecond for which your splash screen should visible to
  //user. here i have taken half second
private static final long SPLASHTIME = 500;

//handler for splash screen
private Handler splashHandler = new Handler() {
     @Override
     public void handleMessage(Message msg) {
          switch (msg.what) {
            case STOPSPLASH:
                //Generating and Starting new intent on splash time out 
                Intent intent = new Intent(Splash.this, 
                                         MainActivity.class);
                startActivity(intent);
                    Splash.this.finish(); 
                break;
          }
          super.handleMessage(msg);
     }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);

    //Generating message and sending it to splash handle 
    Message msg = new Message();
    msg.what = STOPSPLASH;
    splashHandler.sendMessageDelayed(msg, SPLASHTIME);
}
}

splash.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:background="@drawable/mydrawable">
     // have a imageview and set background to imageview   

</RelativeLayout>

Using handlers and postdelayed

public class Splash extends Activity {
private static final int SPLASH_TIME = 2 * 1000;// 3 seconds

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);
    ImageView iv= (ImageView) findViewById(R.id.imageView1);
    iv.setBackgroundResource(R.drawable.afor);
    try {
    new Handler().postDelayed(new Runnable() {

        public void run() {

            Intent intent = new Intent(Splash.this,
                MainActivity.class);
            startActivity(intent);

            Splash.this.finish();
        }


    }, SPLASH_TIME);

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


@Override
public void onBackPressed() {
    this.finish();
    super.onBackPressed();
}
}

splash.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:background="#ffffaa">

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
     />

</RelativeLayout>
public class vv extends Activity {
    int b[] = {R.drawable.a, R.drawable.m, R.drawable.b, R.drawable.j, R.drawable.er, R.drawable.chan, R.drawable.vv};
    public ImageView i;
    int z = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        i = (ImageView) findViewById(R.id.image);
        i.setImageResource(b[0]);
        Thread timer = new Thread() {
            public void run() {
                try {
                    sleep(2000);

                    for (z = 0; z < b.length + 2; z++) {
                        if (z < b.length) {
                            sleep(2000);
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    i.setImageResource(b[z]);
                                }
                            });
                        } else {
                            z = 0;

                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("finally");
                }
            }
        };
        timer.start();
    }


}

Perhaps consider using

AsyncTask.execute(new Runnable {
  public void run() {
     splash.setImageResource(R.drawable.square);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM