Java – what is a better way to handle multiple intentions in Android?

We have encountered the following code or similar content many times in Android or Java. This code seems to contain repetition, which is not a good habit at all. There must be some better ways to do this. Is there any shorter code to achieve this goal?

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

resolvent:

Create an ID table for an activity class 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 the switch:

startActivity(new Intent(this), map.get(v.getId()));

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>