3D-kreativ
3D-kreativ

Reputation: 9297

Trying to use Toast message, but get error

I'm trying to use a Toast message inside a listener method, but I get an error saying something like: Toast is not applicable for the argument.. I don't understand this and can't solve this problem without some help? Thanks!

        // Button 1
    button_1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //text_1.setText("New text for first row!"); // Change text
            Toast.makeText(this, "You have clicked on number 1", Toast.LENGTH_LONG).show();
            if(controlImage_1)
            {
                image_1.setImageResource(R.drawable.android_1b); // Change image
                controlImage_1 = false;
            }
            else
            {
                image_1.setImageResource(R.drawable.android_1a); // Change image
                controlImage_1 = true;
            }
            //Toast.makeText(this, "Your download has resumed.", Toast.LENGTH_LONG).show();
        }
    });

Upvotes: 0

Views: 362

Answers (5)

dcanh121
dcanh121

Reputation: 4695

Because you are using it in the onClick Listener method, you cannot use only this as the first parameter.

Toast.makeText(ClassName.this, "You have clicked on number 1", Toast.LENGTH_LONG).show();

Use your classname.this as the first parameter.

Upvotes: 0

Rahul garg
Rahul garg

Reputation: 9362

Try getApplicationContext() as first argument for Toast.makeText or MyActivity.this

here in your code , this refers to the View

Also, if button_1 needs to have onclick listener by default and you are using API > 7,its nice to define onclick="myclickfunction" in the layout itself. Cleans up your code and easy to modify...

Upvotes: 0

DRiFTy
DRiFTy

Reputation: 11369

You need to pass in the Context of the current Activity as the first argument. You can't just say this in this case because it is not referring to the application context. You can either create a variable in your on create and use that context or just do this...

Toast.makeText([CLASS_NAME].this, "You have clicked on number 1", Toast.LENGTH_LONG).show();

Replace [CLASS_NAME] with the class that is extending Activity

Upvotes: 0

josephus
josephus

Reputation: 8304

Toast.makeText(this, "You have clicked on number 1", Toast.LENGTH_LONG).show();

Your this in this statement refers to the View.OnClickListener you created. Read more on anonymous inner classes.

Use MyActivity.this instead

Upvotes: 1

Namor Alves
Namor Alves

Reputation: 143

Try it:

Toast.makeText(**YourClassName.this**, "You have clicked on number 1", Toast.LENGTH_LONG).show();

Without * =)

Upvotes: 1

Related Questions