In this short blog post, I’ll write about a pattern I like to use when starting new activities in Android development.
To start a new activity in Android development, we need to instantiate an intent, specify in that intent the current activity’s name and the new activity’s name. The code usually looks something like this.
1 2 3 4 5 6 7 8 |
Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(FromActivity.this, ToActivity.this); startActivity(intent); } }); |
This is pretty common and straightforward. The one thing I never really liked about this though, especially if the ToActivity
is an activity that’s called often from different places, is how I always have to manually instantiate a new intent and then specify which activity I am trying to open.
Instead of manually instantiating a new intent in an Activity file every time I want to open a new intent, I like to set a static method on the Activity class that needs to be opened. For example, in our example, in our ToActivity
class file, I would have a static method called startActivity
that looks like this.
1 2 3 4 5 6 7 8 9 10 11 12 |
public class ToActivity extends AppCompatActivity { public static void startActivity(Activity startingActivity) { startingActivity.startActivity(new Intent(startingActivity, ToActivity.class)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_medical_id); // Some more code below here... } } |
And then in our original code to open our new activity, we would write it like this
1 2 3 4 5 6 7 |
Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ToActivity.startActivity(getActivity()); } }); |
I find this to be much cleaner compared to our previous version. Also, if we need to start up ToActivity
from more than one place, this pattern allows us to reuse the startActivity
method, thus reducing duplication.