Why does the onclick attribute of textview add clickable settings?

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.