如何在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) ;
这是我的问题
buttonname.setOnClickListener(this); //as I understand it, the "**this**" denotes the current `view(focus)` in the android program
然后你的 OnClick()
事件...
then your OnClick()
event...
问题:
当我输入this"时,它说:
When I type in the "this", it says:
setOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)
我不知道为什么?
这里是 .java 文件中的代码
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;
}
推荐答案
View 中的 SetOnClickListener (Android.View.view.OnClickListener) 不能应用于 (com.helloandroidstudio.MainActivity)
SetOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)
换句话说(由于您当前的情况)您的 MainActivity 需要实现 OnClickListener:
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
}
这个:
buttonname.setOnClickListener(this);
意味着你想为你的按钮分配侦听器在这个实例上" ->
这个实例代表OnClickListener,因此您的类必须实现该接口.
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) {
}
});
这篇关于如何在android studio中添加按钮点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!