Thursday, October 30, 2014

Toast

Today I worked on adding more to my hello world app. I decided on adding a button that would display text such as "Hello World" and this pop up is referred to as toast. I used the references at developer.android.com and I mainly used this source along with this one.
  • A toast is just a widget that can show pop ups to users
  • I kept getting errors that were simply fixed by adding some import statements. So I just have to keep in mind that if something is underlined red then there may be a good chance that I am just missing an import statement.
  • I also wasn't placing things the variables in the correct place which means that I have to remember to define my variables in the correct place
  • Apparently you don't need to add any xml, you can just use a function called setGravity like below where bigger numbers move it further down or right so right now it's in the top left corner
    • toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0); 
        
  • If you want a custom pop up image you need to make your own xml so I guess this would allow you to adjust size or color, etc
    So you can see the little message in the corner, it's currently pretty small and only shows up for a short period of time and you can see the majority of the code below. I'll explain it real quick although I could be wrong... so first the code finds the button which I just gave the id "button". Then there is a function to do something when the button is clicked. After that I specified the variables and you can probably guess what each does, like "LENGTH_SHORT" makes the pop up come up for a short time. Then a new Toast called "toast" is made where the text is made and then shown. I don't really get what Context does so I'll have to read up on that.
     final Button button = (Button) findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Context context = getApplicationContext();
                    CharSequence text = "Hello toast!";
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                    toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

    1 comment:

    1. This is a good post, Aki, but it is Thursday. What happened to Monday, Tuesday, and Wednesday?

      ReplyDelete