简体   繁体   English

如何在android studio中添加按钮点击事件

[英]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...然后你的OnClick()事件...

Problem:问题:

When I type in the "this", it says:当我输入“this”时,它说:

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这是 .java 文件中的代码

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;

    }

SetOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity) View中的SetOnClickListener(Android.View.view.OnClickListener)不能应用于(com.helloandroidstudio.MainActivity)

This means in other words (due to your current scenario) that your MainActivity need to implement OnClickListener :这意味着换句话说(由于您当前的情况)您的 MainActivity 需要实现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.意味着您要为“在此实例上”的Button 分配侦听器->此实例代表OnClickListener ,因此您的类必须实现该接口。

It's similar with anonymous listener class (that you can also use):它类似于匿名侦听器类(您也可以使用):

buttonname.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View view) {

   }
});
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
    }
}

When you define an OnClickListener (or any listener) this way当您以这种方式定义OnClickListener (或任何侦听器)时

btnClick.setOnClickListener(this);

you need to implement the OnClickListener in your Activity .您需要在Activity implement OnClickListener

public class MainActivity extends ActionBarActivity implements OnClickListener{
public class MainActivity extends AppCompatActivity implements View.OnClickListener

Whenever you use (this) on click events, your main activity has to implement ocClickListener.每当您在点击事件上使用 (this) 时,您的主要活动都必须实现 ocClickListener。 Android Studio does it for you, press alt+enter on the 'this' word. Android Studio 会为您完成,在“this”字样上按 alt+enter。

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();
    }
}

Start your OnClickListener, but when you get to the first set up parenthesis, type new, then View, and press enter.启动您的 OnClickListener,但是当您到达第一个设置括号时,键入 new,然后键入 View,然后按 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.
    }
});

//as I understand it, the "this" denotes the current view(focus) in the android program //据我所知,“this”表示android程序中的当前视图(焦点)

No, "this" will only work if your MainActivity referenced by this implements the View.OnClickListener , which is the parameter type for the setOnClickListener() method.不,“this”仅在this引用的MainActivity实现View.OnClickListener ,这是setOnClickListener()方法的参数类型。 It means that you should implement View.OnClickListener in MainActivity .这意味着您应该在MainActivity实现View.OnClickListener

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) {

        }

    }
}

I found a video. 我找到了一个视频。 This video guides clearly about the handling a button click. 该视频清楚地指导了如何处理按钮单击。 And now, I knew that there are three ways to handle event click on View in Android. 现在,我知道有三种方法可以处理Android中“视图”上的事件点击。

You can simply set onClickListener on a Button or anything using Lambda Expression which looks like您可以简单地在 Button 或任何使用 Lambda 表达式的东西上设置 onClickListener ,它看起来像

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

buttonname.setOnClickListener(v ->
    {
       //Your Listener Code Here
    });

in Activity java class you would need a method first to find the view of the button as :在 Activity java 类中,您首先需要一个方法来查找按钮的视图:

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并为您的功能覆盖 onClick 方法。我在这里找到了一个完整的示例: http : //javainhouse.blogspot.in/2016/01/button-example-android-studio.html

Your Activity must implement View.OnClickListener , like this:您的Activity必须实现View.OnClickListener ,如下所示:

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

And inside MainActivity override the method onClick() , like this:MainActivity重写方法onClick() ,如下所示:

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

You need to do nothing but, just type new View.OnClickListener() in your btnClick.setOnClickListener() .您什么都不用做,只需在btnClick.setOnClickListener()键入new View.OnClickListener() 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括号将保持打开状态,只需按回车键,就会像这样创建一个方法,

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.这只是意味着您正在创建 OnClickListener 的新视图并将视图作为参数传递。 Now you can do whatever u were supposed to do, in that onClick(View v) method.现在你可以在 onClick(View v) 方法中做你应该做的任何事情。

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 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());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM