简体   繁体   中英

View and Activity how to share data in android.content.Context?

I want MyView can share data with MyActivity , so I need they can put data into Context and get data from Context , How to do that?

class MyView extends Button {

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);

        put data into context ...

        get data from context ... 
    }

}

class MyActivity extends Activity {

     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.xxx);

         put data into context ...

         get data from context ... 
     } 
}

I know Activity is a instance of Context , and there is Context in the View 's construtor.So I think when the Activity started, At sometime, View is trigger by event, so View put some data in Context , then at sometime, Activity is trigger by event, so it cant get data from 'Context'. I want Context to be a email box which both View and Activity send and get emails from it. I think there is some methods like put(key, val) and get(key) in Context but I not found.

您可以通过在活动类中调用getApplicationContext()getContext()getBaseContext()或this来获取上下文。

@malrok44 's idea is inspired me. This is my solution.

interface Interacton {
      void putData(key, val)
      object getData(key)
}

class MyActivity extends Activity implements Interacton {

     public void oncreate() {
           getData(xx) 
           putData(xx,yy) 
     }

     private Map map = new HashMap  

     public void putData(key, val) {
          map.put(key, val);
     }

     public object getData(key) {
          return map.get(key)
     }
}

class MyView extends Button {

     public MyView(Context context) {
         Interaction ctx = (Interaction)context;
         ctx.put(xx,yy)
         ctx.get(xx)
     }
}

I think ThreadLocal is be ok, but I am not sure it is safe?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM