Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the better way to handle mutiple intents in android?

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);

2 Answers

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()));
like image 139
Doug Stevenson Avatar answered Dec 15 '25 15:12

Doug Stevenson


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);
like image 44
Amy Avatar answered Dec 15 '25 14:12

Amy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!