How to handle button clicks using the XML onClick within Fragments

前端 未结 18 1878
旧时难觅i
旧时难觅i 2020-11-22 01:41

Pre-Honeycomb (Android 3), each Activity was registered to handle button clicks via the onClick tag in a Layout\'s XML:

android:onClick=\"m         


        
18条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 02:05

    I'd like to add to Adjorn Linkz's answer.

    If you need multiple handlers, you could just use lambda references

    void onViewCreated(View view, Bundle savedInstanceState)
    {
        view.setOnClickListener(this::handler);
    }
    void handler(View v)
    {
        ...
    }
    

    The trick here is that handler method's signature matches View.OnClickListener.onClick signature. This way, you won't need the View.OnClickListener interface.

    Also, you won't need any switch statements.

    Sadly, this method is only limited to interfaces that require a single method, or a lambda.

提交回复
热议问题