MainActivity.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package org.uab.android.threading.simplethread;
  2. import android.app.Activity;
  3. import android.graphics.Bitmap;
  4. import android.graphics.BitmapFactory;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.view.View.OnClickListener;
  8. import android.widget.Button;
  9. import android.widget.ImageView;
  10. import android.widget.Toast;
  11. public class MainActivity extends Activity {
  12. Button loadImageButton;
  13. Button sayHelloButton;
  14. ImageView imageView;
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_main);
  19. imageView = (ImageView) findViewById(R.id.imageView1);
  20. loadImageButton = (Button) findViewById(R.id.loadImage);
  21. loadImageButton.setOnClickListener(new OnClickListener() {
  22. @Override
  23. public void onClick(View v) {
  24. loadImage();
  25. }
  26. });
  27. sayHelloButton = (Button) findViewById(R.id.sayhello);
  28. sayHelloButton.setOnClickListener(new OnClickListener() {
  29. @Override
  30. public void onClick(View v) {
  31. Toast.makeText(MainActivity.this, "Hello class!",
  32. Toast.LENGTH_SHORT).show();
  33. }
  34. });
  35. }
  36. public void loadImage() {
  37. // Create a new Thread to load the image
  38. new Thread(new Runnable() {
  39. @Override
  40. public void run() {
  41. // Get a Bitmap from a drawable resource
  42. final Bitmap bitmapImage = BitmapFactory.decodeResource(getResources(), R.drawable.grumpycat);
  43. // Simulate a long-running operation
  44. try {
  45. Thread.sleep(5000);
  46. } catch (InterruptedException e) {
  47. e.printStackTrace();
  48. }
  49. // Set the decoded bitmap as the ImageView's source
  50. // This doen't work in Android
  51. if ( bitmapImage != null )
  52. imageView.setImageBitmap(bitmapImage);
  53. }
  54. }).start(); // Executes the newly created thread
  55. }
  56. }