Click here to Skip to main content
15,920,217 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
package com.example.button;

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

public class MainActivity extends AppCompatActivity {

Button button;


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

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


}

@Override
protected void onClick(View view) {

button.setOnClickListener(new View.OnClickListener());
Toast t = Toast.makeText(MainActivity.this, "U Have Clicked Me", Toast.LENGTH_LONG);
t.show();

}


}


I wrote this code so that when i press the button my outout will be-U Have Clicked Me

What I have tried:

package com.example.button;

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

public class MainActivity extends AppCompatActivity {

Button button;


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

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


}

@Override
protected void onClick(View view) {

button.setOnClickListener(new View.OnClickListener());
Toast t = Toast.makeText(MainActivity.this, "U Have Clicked Me", Toast.LENGTH_LONG);
t.show();

}


}
Posted
Updated 18-Jun-17 2:28am
Comments
wseng 23-Jun-17 0:28am    
please wrap your code

1 solution

You missed to set setOnClickListener to button.

   public class MainActivity extends AppCompatActivity implements View.OnClickListener{

   Button button;

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

   button = (Button) findViewById(R.id.button);
   button.setOnClickListener(this); // add this line
  }

  @Override
  protected void onClick(View view) {
    Toast t = Toast.makeText(MainActivity.this, "U Have Clicked Me",Toast.LENGTH_LONG);
    t.show();
  }
}

And also, please format your code nicely so it more readable.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900