Himanshu Rahi
Himanshu Rahi

Reputation: 21

Button.OnClickListener() gives error

Am new in Android Programming basically am making an app in which when i click button the text gonna change... here is my code..

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

    Button HimanshuButton = (Button) findViewById(R.id.HimanshuButton);
    HimanshuButton.setOnClickListener(
            new Button.OnClickListener() {
                public void OnClick(View v){
                    TextView HimanshuText = (TextView)findViewById(R.id.HimanshuText);
                    HimanshuText.setText("Great Himanshu Rahi");

in this Button.OnClickListener gives me an error like a red under line..

Upvotes: 2

Views: 94

Answers (3)

nikhil nangia
nikhil nangia

Reputation: 581

A better and neat way to do this will be Using this method, It will ask you to implement setOnClickListener Interface once you do this HimanshuButton.setOnClickListener(this);

protected void onCreate(Bundle savedInstanceState) {
    Button HimanshuButton = (Button) findViewById(R.id.HimanshuButton);
    HimanshuButton.setOnClickListener(this);
}

@override
public void onClick(){
    TextView HimanshuText = (TextView)findViewById(R.id.HimanshuText);
    HimanshuText.setText("Great Himanshu Rahi");
}

Upvotes: 2

guipivoto
guipivoto

Reputation: 18677

Change:

new Button.OnClickListener()

To:

new View.OnClickListener()

UPDATE:

There's another error: It is onClick and not OnClick. First letter of onClick() must be in lower case.

Full code:

Button HimanshuButton = (Button) findViewById(R.id.HimanshuButton);
HimanshuButton.setOnClickListener(
        new View.OnClickListener() {
            public void onClick(View v) {
                TextView HimanshuText = (TextView) findViewById(R.id.HimanshuText);
                HimanshuText.setText("Great Himanshu Rahi");
            }
        });

Upvotes: 1

Hardik Parmar
Hardik Parmar

Reputation: 712

Do this way for any android widget ClickListener

Button HimanshuButton = (Button) findViewById(R.id.HimanshuButton);

        HimanshuButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                TextView HimanshuText = (TextView) findViewById(R.id.HimanshuText);
                HimanshuText.setText("Great Himanshu Rahi");
            }
        });

Upvotes: 1

Related Questions