0

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.

lionyu
  • 593
  • 3
  • 5
  • 14
  • You cant. You should do it with accessors and callbacks. – malrok44 Feb 25 '16 at 14:38
  • You should ask more clearly about the scenario you want, since there are many solutions available – Farhad Feb 25 '16 at 14:41
  • If you only want to exchange data you could create a MyView Object in your MyActivity class. Then the MyActivity class can put itself or just the data you want to exchange in the constructor or other functions – Joh Feb 25 '16 at 14:50

2 Answers2

0

You can get the context by invoking getApplicationContext(), getContext(), getBaseContext(), or this when call it in the activity class.

jemiloii
  • 24,594
  • 7
  • 54
  • 83
0

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

lionyu
  • 593
  • 3
  • 5
  • 14