We come across the following code or something similar in Android or Java many times. This code seems like containing repetitions and this is not a good practice at all. There must be some better way to do this. is there any shorter code to achieve this?
Intent intent=null;
switch (v.getId()) {
case R.id.details:
intent = new Intent(this, DetailsActivity.class);
break;
case R.id.apply:
intent = new Intent(this, ApplyActivity.class);
break;
case R.id.edit:
intent = new Intent(this, EditActivity.class);
break;
case R.id.upload:
intent = new Intent(this, UploadActivity.class);
break;
case R.id.call:
intent = new Intent(this, CallActivity.class);
break;
}
startActivity(intent);
Make a table of ids to activity classes in a static initializer or constructor:
HashMap<Integer, Class<?>> map = new HashMap<>();
map.put(R.id.foo, Foo.class); // repeat for each id/class pair
Then use the map instead of a switch:
startActivity(new Intent(this), map.get(v.getId()));
As I commented use setClass method instead. Do like this.
Set your Activity classname to button tag and get this tag on button click.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="YourActivityName"
/>
Java Code
String classname = (String) textView.getTag();
intent.setClassName(getPackageName().toString(), classname)
startActivity(intent);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With