android activity class constructor working

前端 未结 4 2028
陌清茗
陌清茗 2021-01-01 00:58

When considering the case with android activity, the first method to work is its onCreate method..right?

Suppose i want to pass 2 parameters to android

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-01 01:35

    Not sure why you would not want to use the intent params. That is what they are there for. If you need to pass the same parameters from different places in your application, you could consider using a static constructor that builds your intent request for you.

    For example:

    /**
     * Sample activity for passing parameters through a static constructor
     * @author Chase Colburn
     */
    public class ParameterizedActivity extends Activity {
    
        private static final String INTENT_KEY_PARAM_A = "ParamA";
    
        private static final String INTENT_KEY_PARAM_B = "ParamB";
    
        /**
         * Static constructor for starting an activity with supplied parameters
         * @param context
         * @param paramA
         * @param paramB
         */
        public static void startActivity(Context context, String paramA, String paramB) {
            // Build extras with passed in parameters
            Bundle extras = new Bundle();
            extras.putString(INTENT_KEY_PARAM_A, paramA);
            extras.putString(INTENT_KEY_PARAM_B, paramB);
    
            // Create and start intent for this activity
            Intent intent = new Intent(context, ParameterizedActivity.class);
            intent.putExtras(extras);
            context.startActivity(intent);
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // Extract parameters
            Bundle extras = getIntent().getExtras();
            String paramA = extras.getString(INTENT_KEY_PARAM_A);
            String paramB = extras.getString(INTENT_KEY_PARAM_B);
    
            // Proceed as normal...
        }
    }
    

    You can then launch your activity by calling:

    ParameterizedActivity.startActivity(this, "First Parameter", "Second Parameter");

提交回复
热议问题