Java – The OnClick() method does not work in a TextView

The OnClick() method does not work in a TextView… here is a solution to the problem.

The OnClick() method does not work in a TextView

I have a textView and OnClick method to navigate another activity. However, if I press that text, it doesn’t navigate. But if I use Button instead of TextView, it works perfectly. Can’t use the OnClick method in a TextView?

My XML code;

<TextView
    android:onClick="webClick"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:layout_marginLeft="17dp"
    android:layout_marginTop="19dp"
    android:text="Chapter 1"
    android:textSize="25dp" />

My Java code:

public void webClick(View v) {
    Intent intent = new Intent(this, Webview.class);
    startActivity(intent);
}

Solution

Add this property to the textview

       android:clickable="true"

http://developer.android.com/reference/android/view/View.html#attr_android:clickable

android:clickable

Defines whether this View reacts to click events.

Must be a boolean value, “true” or “false”.

This can also be for a resource that contains a value (in the form “@[package:]type:name”) or a theme attribute (in the format “?[ package:][type:]name”) refers to this type.

This corresponds to the global property resource symbol clickable.

Related methods
setClickable( boolean value).

Related Problems and Solutions