How do I instantiate a class in android which is also an activity?

前端 未结 4 503
深忆病人
深忆病人 2021-01-29 00:39

In android, how can I create a constructor for a class which is also an Activity?

My problem is,

I want to have two activity cl

4条回答
  •  伪装坚强ぢ
    2021-01-29 01:02

    Activities can't have user defined constructors, only the default one; they can be instantiated only indirectly via intent creation. If you need to pass data between activities, do it by putting extras to bundles, for example:

    bundle.putInt("dist",dist);
    

    then you can extract the data from bundle by

    int dist = bundle.getInt("dist");
    

    Put extras before starting the activity:

    Intent i = new Intent(this, CalculateFare.class);
    Bundle b = new Bundle();
    
    b.putInt("dist",dist);
    i.putExtras(b);
    startActivity(i);
    

    and then read the extras in the onCreate method:

    public void onCreate(Bundle savedInstanceState)
    {
       super.onCreate(savedInstanceState);
    
       Bundle b = getIntent().getExtras();
       int dist;
    
       if (b != null)
       {
          dist = b.getInt("dist");
       }
    }
    

提交回复
热议问题