androidxml-layout

My Button is not responding in android studio


When i run the app. The buttons refuse to respond. I set a Toast and a logcat to check for response. but non. please help resolve

this is my source code

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:id="@+id/textView" />

<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="14dp"
    android:id="@+id/button"
    tools:onClick="topClick" />

<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="14dp"
    android:id="@+id/button2"
    tools:onClick="bottomClick" />

and for my java methods;

public class MyActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_layout);

        //Testing the Toast and Log in action
        Toast.makeText(this, "Can you see me?", Toast.LENGTH_SHORT).show();

        Log.i("info", "Done creating the app");
    }


    //creating method topclick
    public void topClick(View v) {
        Toast.makeText(this, "Top button clicked", Toast.LENGTH_SHORT).show();

        Log.i("info", "The user clicked the top button");
    }

    //creating method bottomclick
    public void bottomClick(View v) {
        Toast.makeText(this, "Bottom button clicked", Toast.LENGTH_SHORT).show();

        Log.i("info", "the user clicked the bottom button");
    }

}

Solution

  • Replace

    tools:onClick

    with

    android:onClick

    for both buttons.

    For more context that will help you understand why this change is required, read up on the tools namespace:

    Android Studio supports a variety of XML attributes in the tools namespace that enable design-time features (such as which layout to show in a fragment) or compile-time behaviors (such as which shrinking mode to apply to your XML resources). When you build your app, the build tools remove these attributes so there is no effect on your APK size or runtime behavior.