In http://smartcloudblog.blogspot.com/2011/09/android-onclicklisteners-vs.html
I mentioned four onclick implementation methods. I like the fourth one, that is, configuration in XML files, which is simple for everyone. So I tried textview and button to make a simple demo.
It is found that it is easy to use when the button is used, but not when used as textview. When textview. setonclicklinstener is used?
The source code is the best mentor-this is what the fat brother told me, so I used F3 and F4 to explore the source code and found a piece of code in the view
** * Register a callback to be invoked when this view is clicked. If this view is not * clickable, it becomes clickable. * * @param l The callback that will run * * @see #setClickable(boolean) */ public void setOnClickListener(OnClickListener l) { if (!isClickable()) { setClickable(true); } mOnClickListener = l; }
FoundSetonclicklistenerI did two things in total
1. Make this view clickable.
2. Register and handle events
Then, let's test whether it is correct. check a few lines of code to verify the default clickable value of textview and its change.
boolean clickable = this.findViewById(R.id.mTextView).isClickable(); Log.d("Before setOnClickListener", String.valueOf(clickable)); this.findViewById(R.id.mTextView).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(TestAndroidXMLOnclickActivity.this, "from onclick inner class", Toast.LENGTH_SHORT).show();}}); clickable = this.findViewById(R.id.mTextView).isClickable(); Log.d("After setOnClickListener", String.valueOf(clickable));
The result is as follows:
The conjecture is correct.
With the above experiments, we can find the cause of the problem:
Textview does not support click by default. If onclick aattribute is configured in XML, it must be associated with clickable and true.