Zion Cohen
Zion Cohen

Reputation: 352

android.widget.Button does not have setOnClickListener method

I am totally new at Android and Android Studio. I am trying to write very simple application with a Button: here is my code: {

public class MainActivity extends AppCompatActivity {

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

    Button addButton = (Button) findViewById(R.id.addButton);
    Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        }
    });
}

The problem is the i am getting error "cannot resolve symbol setOnClickListener" and the setOnClickListener appear at red. when i am trying to do auto completion of setOnClickListener at part of addButton, it appears that addBurron does not have this method.

can you please help?

Upvotes: 0

Views: 420

Answers (1)

forpas
forpas

Reputation: 164099

Replace this:

Button.setOnClickListener()

with:

addButton.setOnClickListener()

you must set the listener to the object addButton and not the class Button.
Also this code:

Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    }
});

must be placed inside a method like onCreate().

Upvotes: 1

Related Questions