Communication between TabActivity and the embedded activity

后端 未结 5 798
Happy的楠姐
Happy的楠姐 2021-01-14 15:44

I am trying to figure out the best practice of communication between a TabActivity and the child activity embedded in this TabActivity.

In my TabActivity, there is a

5条回答
  •  离开以前
    2021-01-14 16:45

    Couple of design issues with this, but overall it seems reasonable.

    I would forgo the static instance in the ChildActivity class. Why? Well, think about the relationship you're modeling. A TabActivity has a ChildActivity. This is textbook composition, and would be accomplished by adding a ChildActivity field to the TabActivity class, like so:

     public class TabActivity {
    
        private ChildActivity child;
    
        //remember to initialize child in onCreate
    
        //then, call methods using child.changeUI();, for example
    
    } 
    

    This is better, because A) now I can have multiple instances of TabActivity and ChildActivity that won't interfere with each other (before, it was just a static variable, so only one ChildActivity could be used), and B) the ChildActivity is encapsulated inside the TabActivity class... before, it was a public field, meaning anything can use and modify it (might not be desirable; can often lead to some strange runtime bugs as well as messy, tied-together code) - we changed it to a private field, because we don't really want other classes accessing it in unexpected ways.

    The only thing you may need access to from the ChildActivity is the parent (TabActivity). To do this, add the following methods and field to the ChildActivity class, and call the registerParent() method after constructing the ChildActivity:

    public class ChildActivity ...{
    
    private TabActivity parent;
    
    public void registerParent(TabActivity newParent){
        if (newParent != null){
            parent = newParent;
        }
    }
    }
    

    So, if you need access to the parent TabActivity from the child, just call parent.someMethod();

    It would also be wise to access fields like parent and child through getters and setters; it might save you some time in the long run.

提交回复
热议问题