开发者

Why can't java subordinate object access parent field?

I have an object that I instantiate twice, and each one needs to affect something in the other object. Yes, it's ugly, but in Android, I want to make a radio button in one display/tab match the state in another display/tab. I suppose I could have a method in the parent that updates both instantiations of the radio button, that'd probably be a better way to do it. But I don't understand why what I've done below doesn't work and I'd like to understand why even if I don't use it.

I'll just use 'someField' for this example as the cross-access field. I pass 'this' into each instantiated object for who the parent is, then I should be able to access a field in the other 'brother' object thru the parent object I would think, but it doesn't seem to work. Here's a simplified version of the code (actually the two classes are in two files of course):

public class EtMain extends TabActivity  {
    public WxFields  mDepWx;
开发者_C百科    public WxFields  mArrWx;

    public void onCreate(Bundle savedInstanceState) {
        mDepWx = new WxFields(this);
        mArrWx = new WxFields(this);
    }
}

public class WxFields {
    private Activity mParent; // Main Window object
    public int someField;

    public WxFields(Activity myParent) {
        mParent = myParent;
    }

    public void someSetup() {
        Button mButton = (Button) mParent.findViewById(R.id.someRes); //<---mParent works here
        mParent.mArrWx.someField = 0; //<------------ mArrWx cannot be resolved
        //I don't seem to be able to access a field in the parent object
        //Yes, it's not symmetrical, but the code is just for illustration purposes

    }
}


Actually, if you declare mParent as EtMain and not as Activity, it will work (though it would be ugly...)

Activity doesn't have such field (mArrWx)

public class EtMain extends TabActivity  {
    public WxFields  mDepWx;
    public WxFields  mArrWx;

    public void onCreate(Bundle savedInstanceState) {
        mDepWx = new WxFields(this);
        mArrWx = new WxFields(this);
    }
}

public class WxFields {
    private EtMain mParent; // Main Window object
    public int someField;

    public WxFields(EtMain myParent) {
        mParent = myParent;
    }

    public void someSetup() {
        Button mButton = (Button) mParent.findViewById(R.id.someRes); //<---mParent works here
        mParent.mArrWx.someField = 0;
    }
}


It looks like you'll have to cast mParent to type EtMain in order for the field to be visable.
mArrWx is not a member of type Activity.


I would have guessed that you'd use a Listener implementation that would take the references of the objects that need to be kept in synch. The action method would check to see which was updated and synch up the other.

http://developer.android.com/guide/topics/ui/ui-events.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜