User44 User44 - 2 months ago 10
Java Question

Error: setOnClickListener cannot be resolved

I encountered an issue and couldn't resolve in

Android Studio
. The setOnClickListener remains red and doesn't work unless I get rid of my "loseStarter1" button name.
Note: Starter1 is a button, I'm trying to make it disappear when clicked by the user. My real code starts when I introduce the loseStarter1 button.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class game1 extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game1);
}

Button loseStarter1;

loseStarter1 = (Button) findViewById(R.id.Starter1);
loseStarter1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loseStarter1.setVisibility(View.GONE);
}
})

}


Much appreciated.

Answer

You're missing a semicolon to end the new View.OnClickListener() { ... statement as well as that block not being inside of a method.

Not only move this code into the onCreate method, make sure you end it with a semicolon.

loseStarter1 = (Button) findViewById(R.id.Starter1);
loseStarter1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        loseStarter1.setVisibility(View.GONE);
        }
    }); // Add the semicolon here

It should look like this:

public class game1 extends AppCompatActivity {

    Button loseStarter1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game1);

        loseStarter1 = (Button) findViewById(R.id.Starter1);
        loseStarter1.setOnClickListener(new View.OnClickListener() {
            @Override
             public void onClick(View v) {
                loseStarter1.setVisibility(View.GONE);
            }
        }); //added semicolon

    } // ends onCreate method
} // ends class
Comments