Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : Why onClick method is not working?

<uses-sdk android:minSdkVersion="8" />

onClick method defined in xml

 <TextView
    android:id="@+id/titlemainpage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"       
    android:text="Social To Dos"   
    android:onClick="testing" />

testing method used in java class is

public void testing(View v){

    Toast.makeText(this, "Clicked", Toast.LENGTH_LONG).show();

    textview.setTextColor(Color.CYAN);
}
like image 266
Shahzad Imam Avatar asked Mar 26 '12 07:03

Shahzad Imam


People also ask

How to use onClick method in android?

When the user clicks a button, the Button object receives an on-click event. To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.

How to give action to Button in android studio?

To add actions to the action bar, create a new XML file in your project's res/menu/ directory. The app:showAsAction attribute specifies whether the action should be shown as a button on the app bar.


3 Answers

Add one more attribute to the textview in xml:

android:clickable="true"

like image 115
Android Killer Avatar answered Sep 27 '22 20:09

Android Killer


Buttons are by default clickable but TextViews are not. Unless you explicitly setup the onClick listener at runtime textViews won't be clickable on pre-Lollipop devices.

So if you want to make a TextView clickable which is hooked with a listener in XML layout file you should use

android:clickable="true"
like image 38
Samuel Robert Avatar answered Sep 27 '22 20:09

Samuel Robert


Dont forget to remove the on click listener (if you have set that programmatically inside the containing activity).

like image 25
Vigneshwaran.m Avatar answered Sep 27 '22 19:09

Vigneshwaran.m