Need to handle click from NON-Activity( .java ) class

前端 未结 3 563
深忆病人
深忆病人 2021-01-19 18:43

i have one main Activity class which contains huge amount of code/data. So i want to make it short and readable so i want to create one .java file which handle the some func

3条回答
  •  执笔经年
    2021-01-19 19:14

    You can just implement your onclick listener in your main class BUT use an interface to externalise the content of the listener in an other Class.

    Exemple :

    Create a class ManageClick.java that contain constructor, several methods and objects.

    An attribute

    public OnClickListenerCustom _onClickListenerCustom;
    

    And an interface

    Interface OnClickListenerCustom{
        public void onclick();
        public void onItemClick();
    }
    

    and another method like setOnClickListenerCustom :

    public void setOnClickListenerCustom(OnClickListenerCustom listener){
        this._onClickListenerCustom = listener;
    }
    

    In your main Class MainActivity.java you implement the onclick() method, in the oncreate you set the listener :

    public ManageClick _clickManager;
    
    _clickManager = new ManageClick();
    _clickManager.setOnClickListener((OnClickListenerCustom) this.MainActivity);
    

    To finish in the onclick method you only need to call

    _clickManager.onClick() or _clickManager.onItemClick()
    

提交回复
热议问题