shehzy shehzy - 4 months ago 17
Android Question

Button click listener in xml

For button click listeners code runs fine when click listeners are defined in the activity but facing problem when defining click listener in the xml, no spelling mismatch

following error on logcat appears when listener are defined in xml, why?

java.lang.IllegalStateException: Could not find method addButtonClicked(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'addButton'

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="@+id/addButton"
android:layout_marginTop="50dp"
android:onClick="addButtonClicked"
android:layout_below="@+id/inputField"
android:layout_alignLeft="@+id/inputField"
android:layout_alignStart="@+id/inputField" />


This is Activity Class

When click listener is defined in xml

public void addButtonClicked()
{

String text = inputField.getText().toString();
Products p = new Products(text);
dbObj.addProduct(p);
printDatabase();

}


When click listener is defined from Activity, This works fine

addButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{

String text = inputField.getText().toString();
Products p = new Products(text);
dbObj.addProduct(p);
printDatabase();

}
});

Answer

Add this to you activity:

    public void addButtonClicked(View view) {
     //Your code here
    }