passing object to activity

前端 未结 3 1457
暗喜
暗喜 2021-01-16 20:39

Can i initialize object in my first activity and you it in all activity???

public class Calc{
    int x;
    int y;
    public Calc(int x, int y) {
       th         


        
3条回答
  •  旧时难觅i
    2021-01-16 21:13

    Use Application class by extending it and writing your custom Application class, and keep your objects in this class that you need in your cross Activities

    class MyApplication extends Application{
        Object a;
    
        public void setA(Object a){
             this.a = a;
        }
    
        public Object getA(){
             return a;
        }
    
    }
    

    Now lets suppose in your A activity you create object of class Object and want to use it in your B Activity.

    do it this way,

    class ActivityA extends Activity(){
    
    ...
    // some where in activity, set your object this way.
         Object aObj = new Object();
         ((MyApplication)getApplication()).setA(aObj);
    
    
    ...
    
    }
    
    class ActivityB extends Activity(){
    
    ...
    // some where in activity, get your object this way.
         Object aObj = ((MyApplication)getApplication()).getA( );
    
    
    ...
    
    }
    

    You need to tell your androidManifest.xml about your extended Application class.

提交回复
热议问题