CRTC Electronics

Click here to edit subtitle

Methods / Funtions

Methods or functions are actions. They can take many lines of code down to one line, like a summery.  If you have a page of code that calculates and make a shopping list you can put the code in a method like makeMyShoppinList().

Here is a method that takes a string and uses it to make a toast.

private void toast(final String message) 

{

   final Context context = this;

   runOnUiThread

   (

      new Runnable() 

      {

         @Override

         public void run() 

         {

            Toast.makeText(context, message, Toast.LENGTH_LONG).show();

         }

      }

   );

}

Syntax

private vs public = only certain parts of the code can use this method

void = returns nothing, int = returns an integer, ...

name of the method

( ) arguments or variables that the method requires if any

{ } this is were you put your code that does something

private void saySomething() 

{

   toast("hi, i just said something!");

}


Calling the Method

this is how you call your method

saySomething();

Challenge

Make a method that when called will call the above method toast.


Then in the onCreate() method call your new method.

private void saySomething() 

{

   toast("hi, i just said something!");

}