Passing function as a parameter in java

后端 未结 6 1003
南笙
南笙 2020-11-28 22:13

I\'m getting familiar with Android framework and Java and wanted to create a general \"NetworkHelper\" class which would handle most of the networking code enabling me to ju

6条回答
  •  一个人的身影
    2020-11-28 22:56

    Reflection is never a good idea since it's harder to read and debug, but if you are 100% sure what you're doing, you can simply call something like set_method(R.id.button_profile_edit, "toggle_edit") to attach a method to a view. This is useful in fragment, but again, some people would consider it as anti-pattern so be warned.

    public void set_method(int id, final String a_method)
    {
        set_listener(id, new View.OnClickListener() {
            public void onClick(View v) {
                try {
                    Method method = fragment.getClass().getMethod(a_method, null);
                    method.invoke(fragment, null);
                } catch (Exception e) {
                    Debug.log_exception(e, "METHOD");
                }
            }
        });
    }
    public void set_listener(int id, View.OnClickListener listener)
    {
        if (root == null) {
            Debug.log("WARNING fragment", "root is null - listener not set");
            return;
        }
        View view = root.findViewById(id);
        view.setOnClickListener(listener);
    }
    

提交回复
热议问题