Search code examples
androidandroid-layoutandroid-custom-viewandroid-context

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.


Solution

  • @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?