I want to implement a click listener for a button on my main view. My code is something like below
protected void onCreate(Bundle savedValues) {
...
// Capture our button from layout
Button button = (Button)findViewById(R.id.btnFinish);
// Register the onClick listener with the implementation above
button.setOnClickListener(mFinishListener);
...
}
private OnClickListener mFinishListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
But shows me error as follows
The method se开发者_JAVA百科tOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (DialogInterface.OnClickListener) MobileTrackerActivity.java /MobileTracker/src/com/example/mobiletracker line 37 Java Problem
I have no idea what to do. Please help.
You are not using the correct interface to instantiate the mFinishLinstener
variable...
It is possible you have an import specifying DialogInterface
and that is confusing the view.
Try specifying View.OnClickListener
explicitly.
private View.OnClickListener mFinishListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
As per my opinion Best way to implement On click event for the Button.
Instead of applying an OnClickListener to the button in your activity, you can assign a method to your button in the XML layout, using the android:onClick attribute. For example:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/self_destruct"
android:onClick="selfDestruct" />
Now, when a user clicks the button, the Android system calls the activity's selfDestruct(View) method. In order for this to work, the method must be public and accept a View as its only parameter. For example:
public void selfDestruct(View view) {
// Kabloey
}
Note: The above code is given in Android SDK - Button.
try this code :::
final Button button = (Button) findViewById(R.id.btnFinish);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
Simply try this one as:
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// do something when the button is clicked
}
};
you can also use like below code..
Button button = (Button)findViewById(R.id.btnFinish);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v)
{
//Write Your code here
}
});
You can also declare the onclick in the xml.
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onclick="buttonClick" />
And in your code you would define the function as:
public void buttonClick(View view)
{
// handle click
}
精彩评论