Trigger onitemselected event when using reflection to let spinner select the same option

Source: Internet
Author: User

Look at the source code, spinner judge whether to trigger Onitemselected, is in its base class Adapterview inside Do:

    void Checkselectionchanged () {        if (mselectedposition! = moldselectedposition) | | (Mselectedrowid! = Moldselectedrowid)) {            selectionchanged ();            Moldselectedposition = mselectedposition;            Moldselectedrowid = Mselectedrowid;        }    }

methods checkselectionchanged and variable moldselectedposition are adapterview private, and we cannot inherit spinner overrides. However, using Java 's reflection, we can violently modify the value of moldselectedposition:

New Onitemselectedlistener () {@Overridepublic void onitemselected (adapterview<?> arg0, View arg1,int arg2, long ARG3) {//TODO auto-generated method Stubtry {//The following three lines of code is the solution to the problem field field = AdapterView.class.getDeclaredField (" Moldselectedposition "); Field.setaccessible (true);//Set Moldselectedposition accessible Field.setint (spinner, Adapterview.invalid_position); Set the value of Moldselectedposition} catch (Exception e) {e.printstacktrace ();}} @Overridepublic void onnothingselected (adapterview<?> arg0) {//TODO auto-generated Method stub}};

Every time we choose, we change the value of moldselectedposition so that every time mselectedposition! = Moldselectedposition is judged to be true, Then the onitemselected will always be triggeredto achieve our goal.

To implement spinner selected events through code:

Spinner.performitemclick (Suborderslistview.getchildat (ordermenuposition), Ordermenuposition,
Suborderslistview.getitemidatposition (ordermenuposition));

Trigger onitemselected event when using reflection to let spinner select the same option

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.