android:onClick - Add an Action to a TextView Click

How to Add an Action to a TextView Click

android:onClick was added in API Level 4

Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View.

 1. Add a TextView in your main.xml file.

 2. Ensure to change the minSDKVersion to 4, or greater.

 3. Add these imports to the import section.

            import android.view.View;

 4. In the MainActivity.java file, add a new method called onClickmyTextView.

public void onClickmyTextView(View v) {
}

 5. Add your action to the newly created onClickmyTextView.
    For testing purposes, let's add a Toast inside the onClickmyTextView method.
    First, add this import to the imports section.

              import android.widget.Toast;

 6. Add the toast to the onClickmyTextView method.

Toast.makeText(this, "You clicked myTextView", Toast.LENGTH_SHORT).show();

 7. In the main.xml file, add the code below.

  <TextView
        ...
       android:onClick = "onClickmyTextView"
  />

 8. And lastly, we need to make the TextView clickable.

9. Compile and run! Click on the TextView to test!

Related Articles:
Resources: