How to handle button clicks using the XML onClick within Fragments

前端 未结 18 1514
旧时难觅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:03

    Best solution IMHO:

    in fragment:

    protected void addClick(int id) {
        try {
            getView().findViewById(id).setOnClickListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void onClick(View v) {
        if (v.getId()==R.id.myButton) {
            onMyButtonClick(v);
        }
    }
    

    then in Fragment's onViewStateRestored:

    addClick(R.id.myButton);
    

提交回复
热议问题