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

新手上路,请多包涵

所以我做了一些研究,在通过代码将你的按钮定义为一个对象之后

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

这是我的问题

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

那么你的 OnClick() 事件……

问题:

当我输入“this”时,它说:

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

我不知道为什么?

这是 .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;

    }

原文由 user2699451 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 908
2 个回答

View中的SetOnClickListener(Android.View.view.OnClickListener)无法应用于(com.helloandroidstudio.MainActivity)

这意味着(由于您当前的情况)您的 MainActivity 需要实现 OnClickListener

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

这个:

 buttonname.setOnClickListener(this);

意味着您想 “在此实例上” 为您的 Button 分配侦听器 -> 此实例表示 OnClickListener ,因此您的类必须实现该接口。

它类似于匿名侦听器类(您也可以使用):

 buttonname.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View view) {

   }
});

原文由 Simon Dorociak 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

原文由 Mohamed Zidan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题