[java] how to add button click event in android studio

So I have done some research, and after defining you button as an object by the code

private Button buttonname;
buttonname = (Button) findViewById(R.id.buttonnameinandroid) ;

here is my problem

buttonname.setOnClickListener(this); //as I understand it, the "**this**" denotes the current `view(focus)` in the android program

then your OnClick() event...

Problem:

When I type in the "this", it says:

setOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)

I have no idea why?

here is the code from the .java file

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    private Button btnClick;
    private EditText Name, Date;
    private TextView msg, NameOut, DateOut;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnClick = (Button) findViewById(R.id.button) ;
        btnClick.setOnClickListener(this);
        Name = (EditText) findViewById(R.id.textenter) ;
        Date = (EditText) findViewById(R.id.editText) ;
        msg = (TextView) findViewById(R.id.txtviewOut) ;
        NameOut = (TextView) findViewById(R.id.txtoutName) ;
        DateOut = (TextView) findViewById(R.id.txtOutDate) ;
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    public void onClick(View v)
    {
        if (v == btnClick)
        {
            if (Name.equals("") == false && Date.equals("") == false)
            {
                NameOut = Name;
                DateOut = Date;
                msg.setVisibility(View.VISIBLE);
            }
            else
            {
                msg.setText("Please complete both fields");
                msg.setVisibility(View.VISIBLE);
            }
        }
        return;

    }

This question is related to java android button view android-studio

The answer is


SetOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)

This means in other words (due to your current scenario) that your MainActivity need to implement OnClickListener:

public class Main extends ActionBarActivity implements View.OnClickListener {
   // do your stuff
}

This:

buttonname.setOnClickListener(this);

means that you want to assign listener for your Button "on this instance" -> this instance represents OnClickListener and for this reason your class have to implement that interface.

It's similar with anonymous listener class (that you can also use):

buttonname.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View view) {

   }
});

in Activity java class you would need a method first to find the view of the button as :

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

after this set on click listener

btnSum.setOnClickListener(new View.OnClickListener() {

and override onClick method for your functionality .I have found a fully working example here : http://javainhouse.blogspot.in/2016/01/button-example-android-studio.html


public class EditProfile extends AppCompatActivity {

    Button searchBtn;
    EditText userName_editText;
    EditText password_editText;
    EditText dob_editText;
    RadioGroup genderRadioGroup;
    RadioButton genderRadioBtn;
    Button editBtn;
    Button deleteBtn;
    Intent intent;
    DBHandler dbHandler;

    public static final String USERID_EDITPROFILE = "userID";

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

        searchBtn = (Button)findViewById(R.id.editprof_searchbtn);
        userName_editText = (EditText)findViewById(R.id.editprof_userName);
        password_editText = (EditText)findViewById(R.id.editprof_password);
        dob_editText = (EditText)findViewById(R.id.editprof_dob);
        genderRadioGroup = (RadioGroup)findViewById(R.id.editprof_radiogroup);
        editBtn = (Button)findViewById(R.id.editprof_editbtn);
        deleteBtn = (Button)findViewById(R.id.editprof_deletebtn);
        intent = getIntent();


        dbHandler = new DBHandler(EditProfile.this);

        setUserDetails();

        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = userName_editText.getText().toString();

                if(username == null){
                    Toast.makeText(EditProfile.this,"Please enter username to delete your profile",Toast.LENGTH_SHORT).show();
                }
                else{
                    UserProfile.Users users = dbHandler.readAllInfor(username);

                    if(users == null){
                        Toast.makeText(EditProfile.this,"No profile found from this username, please enter valid username",Toast.LENGTH_SHORT).show();
                    }
                    else{
                        dbHandler.deleteInfo(username);
                        Intent redirectintent_home = new Intent("com.modelpaper.mad.it17121002.Home");
                        startActivity(redirectintent_home);
                    }
                }
            }
        });

        editBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String userID_String = intent.getStringExtra(Home.USERID);
                if(userID_String == null){
                    Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
                    Intent redirectintent_home =  new Intent(getApplicationContext(),Home.class);
                    startActivity(redirectintent_home);
                }
                int userID = Integer.parseInt(userID_String);

                String username = userName_editText.getText().toString();
                String password = password_editText.getText().toString();
                String dob = dob_editText.getText().toString();
                int selectedGender = genderRadioGroup.getCheckedRadioButtonId();
                genderRadioBtn = (RadioButton)findViewById(selectedGender);
                String gender = genderRadioBtn.getText().toString();

                UserProfile.Users users = UserProfile.getProfile().getUser();
                users.setUsername(username);
                users.setPassword(password);
                users.setDob(dob);
                users.setGender(gender);
                users.setId(userID);

                dbHandler.updateInfor(users);
                Toast.makeText(EditProfile.this,"Updated Successfully",Toast.LENGTH_SHORT).show();
                Intent redirectintent_home = new Intent(getApplicationContext(),Home.class);
                startActivity(redirectintent_home);
            }
        });

        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               String username = userName_editText.getText().toString();
               if (username == null){
                   Toast.makeText(EditProfile.this,"Please enter a username",Toast.LENGTH_SHORT).show();
               }
               else{
                   UserProfile.Users users_search = dbHandler.readAllInfor(username);


                   if(users_search == null){
                       Toast.makeText(EditProfile.this,"Please enter a valid username",Toast.LENGTH_SHORT).show();
                   }
                   else{
                       userName_editText.setText(users_search.getUsername());
                       password_editText.setText(users_search.getPassword());
                       dob_editText.setText(users_search.getDob());
                       int id = users_search.getId();
                       Intent redirectintent = new Intent("com.modelpaper.mad.it17121002.EditProfile");
                       redirectintent.putExtra(USERID_EDITPROFILE,Integer.toString(id));
                       startActivity(redirectintent);
                   }
               }
            }
        });


    }

    public void setUserDetails(){

        String userID_String = intent.getStringExtra(Home.USERID);
        if(userID_String == null){
            Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
            Intent redirectintent_home = new Intent("com.modelpaper.mad.it17121002.Home");
            startActivity(redirectintent_home);
        }
        int userID = Integer.parseInt(userID_String);
        UserProfile.Users users = dbHandler.readAllInfor(userID);
        userName_editText.setText(users.getUsername());
        password_editText.setText(users.getPassword());
        dob_editText.setText(users.getDob());
    }
}

Start your OnClickListener, but when you get to the first set up parenthesis, type new, then View, and press enter. Should look like this when you're done:

Button btn1 = (Button)findViewById(R.id.button1);

btn1.setOnClickListener(new View.OnClickListener() {            
    @Override
    public void onClick(View v) {
//your stuff here.
    }
});

You need to do nothing but, just type new View.OnClickListener() in your btnClick.setOnClickListener(). I mean you have to type btnClick.setOnClickListener(new View.onClickListener the bracket will remain open, just hit enter then a method will be created like this,

btnClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

It's just mean that you are creating a new view of OnClickListener and passing a view as it's a parameter. Now you can do whatever u were supposed to do, in that onClick(View v) method.


Button button= (Button)findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
    // click handling code
   }
});

package com.mani.smsdetect;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

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

        //Intialization Button

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

        btnClickMe.setOnClickListener(MainActivity.this);
        //Here MainActivity.this is a Current Class Reference (context)
    }

    @Override
    public void onClick(View v) {

        //Your Logic
    }
}

Your Activity must implement View.OnClickListener, like this:

public class MainActivity extends 
Activity implements View.OnClickListener{
// YOUR CODE
}

And inside MainActivity override the method onClick(), like this:

@override
public void onClick (View view){
//here YOUR Action response to Click Button 
}

public class MainActivity extends AppCompatActivity implements View.OnClickListener

Whenever you use (this) on click events, your main activity has to implement ocClickListener. Android Studio does it for you, press alt+enter on the 'this' word.


Different ways to handle button event

Button btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {            
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(context, "Button 1", 
     Toast.LENGTH_LONG).show();
        }
    });

[Check this article for more details about button event handlers]


public class MainActivity extends Activity {

    Button button;

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

        button = (Button) findViewById(R.id.submitButton);
        button.setOnClickListener(new MyClass());

    }

    public class MyClass implements View.OnClickListener {

        @Override
        public void onClick(View v) {

        }

    }
}

//as I understand it, the "this" denotes the current view(focus) in the android program

No, "this" will only work if your MainActivity referenced by this implements the View.OnClickListener, which is the parameter type for the setOnClickListener() method. It means that you should implement View.OnClickListener in MainActivity.


When you define an OnClickListener (or any listener) this way

btnClick.setOnClickListener(this);

you need to implement the OnClickListener in your Activity.

public class MainActivity extends ActionBarActivity implements OnClickListener{

package com.mani.helloworldapplication;

import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {
    //Declaration
    TextView tvName;
    Button btnShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //Empty Window
        super.onCreate(savedInstanceState);
        //Load XML File
        setContentView(R.layout.activity_main);

        //Intilization
        tvName = (TextView) findViewById(R.id.tvName);
        btnShow = (Button) findViewById(R.id.btnShow);

        btnShow.setOnClickListener(this);

    }

    @Override
    public void onClick(View v)
    {
        String name = tvName.getText().toString();
        Toast.makeText(MainActivity.this,name,Toast.LENGTH_SHORT).show();
    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click

Examples related to view

Empty brackets '[]' appearing when using .where SwiftUI - How do I change the background color of a View? Drop view if exists Difference between View and ViewGroup in Android How to make a view with rounded corners? How to remove all subviews of a view in Swift? How to get a view table query (code) in SQL Server 2008 Management Studio how to add button click event in android studio How to make CREATE OR REPLACE VIEW work in SQL Server? Android findViewById() in Custom View

Examples related to android-studio

A failure occurred while executing com.android.build.gradle.internal.tasks "Failed to install the following Android SDK packages as some licences have not been accepted" error Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' Flutter plugin not installed error;. When running flutter doctor ADB.exe is obsolete and has serious performance problems Android design support library for API 28 (P) not working Flutter command not found How to find the path of Flutter SDK