Why TextViews Are Clickable, 42/100 Days of Code
We know Buttons are meant for clicking. So why does Android allow you to click TextViews?
You can see my updated source code example here as well as a video of my research at the bottom of the page.
To answer this question about Textviews, I researched the View class in the Android API. The View class contains attributes and methods for a variety of clickable items available in the Android OS.
The two classes in question, TextView and Button, are considered subclasses, or “children” of the superclass, or “parent”, View. This means Button, TextView, and many other classes inherit the methods and attributes of the View class.
A good analogy of this is motor vehicles. Motor vehicles contain a motor used for movement, and they can be driven. By that definition, cars, trucks and buses, all motor vehicles, contain motors and can also be driven. The View class contains methods used to configure what happens when they are clicked. That being said, since Buttons and TextViews are subclasses of View, they too, can be clicked.
To prove this, I changed the previous ClickingViews project from the last post and replaced the Button buttonRed with a TextView. After updating the layout and changing the object to a TextView, I was still able to change the backgroud of the app by clicking the TextView (see code below).
textViewRed = findViewById(R.id.redTextView); buttonBlue = findViewById(R.id.blueButton); layout = findViewById(R.id.myLayout); textViewRed.setOnClickListener(new View.OnClickListener(){ @Override public void onClick (View v){ layout.setBackgroundColor(Color.RED); } });
Speaking of clicks, next week I will show you how to open a new Activity in your app with the click of a button!
Join the mailing list to see updates like this every week!
Coding Fanatic