In my app i need to show dialogs for a lot of buttons. Therefore i decided to use 1 onClick for a series of buttons. Only the first line where we implement, there is an error. My code is as follows:
import android.app.Activity;
import android.os.Bundle;
import android.app.AlertDialog;
import android.view.View;
public class Trial extends Activity implements View.OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View b1 = findViewById(R.id.button1);
b1.setOnClickListener(this);
View b2 = findViewById(R.id.button2);
b1.setOnClickListener(this);
}
View.OnClickListener yourListener = new View.OnClickListener() {
public void onClick(View v) {
if (v == button1) {
new AlertDialog.Builder(v.getContext())
.setTitle("Paracettamol")
.setMessage(
"This medicine is generally used to cure Fever")
.setNeutralButton("OK", null).show();
} else if (v == button2) {
new AlertDialog.Builder(v.getContext())
.setTitle("sertraline")
.setMessage(
"This medicine is generally used to cure Head aches")
.setNeutralButton("O开发者_如何学PythonK", null).show();
}
}
}
The fifth line(public class Trial extends Activity implements View.OnClickListener ) gives an error as follows:The type trial must implement the inherited abstract method View.OnClickListener.onClick(View). can anyone please help me.
You need to have the following in your class:
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}}
You have 2 options:
have your activity implement
View.OnClickListener
, that means movingpublic void onClick(View v)
in the activityremove
implements View.OnClickListener
and callb1.setOnClickListener(yourListener);
You've got two onClickListeners.
When you say:
class Trial extends Activity implements onClickListener
,
You're declaring that the class Trial
must itself respond to clicks. You therefore need to implement the onClick() method as in Jon's answer.
However, you've also made an internal onClickListener
, called yourListener
. If you want to use this one, you need to point your buttons to it instead of this
, which refers to the parent class. E.g:
b1.setOnClickListener(yourListener);
精彩评论