0

我有一个基于我数据库中的适配器的主 ListView。每个数据库 id 通过 ListView 被“分配”给一个 Activity。在我的 AndroidManifest 中,每个活动都有一个带有自定义操作的意图过滤器。现在有了这个,我不得不创建这个类:

public final class ActivityLauncher {
    private ActivityLauncher() { }

    public static void launch(Context c, int id) {
        switch(id) {
         case 1:
            Intent intent = new Intent();
            intent.setAction(SomeActivity.ACTION_SOMEACTIVITY);
            c.startActivity(intent);
            break;
        case 2:
            ...
            break;
        ...
        }
    }

    private static void st(Context context, String action) {
        Intent intent = new Intent();
        intent.setAction(action);
        context.startActivity(intent);
    }
}

所以我必须手动为 switch 语句创建一个新案例。如果我必须重新排列或删除一个 ID,这会很麻烦。有没有办法解决这个问题?

4

1 回答 1

0

我不完全确定你的推理,但这是一个平局。制作一个封装您想要的行为的对象。

public class User {
    private static final User[] users = new User[2];
    static {
         user[0] = new User(0, "Action_0");
         user[1] = new User(1, "Action_1");
    }

    private final int id;
    private final String action;

    public User(int id, String action){
          this.id = id;
          this.action = action;
    }

    public int getId(){
           return this.id;
    }

    public Intent getIntent(){
           Intent intent = new Intent();
           intent.setAction(this.action);
           return intent;
    }

    public static User getUser(int id){
        for(int i=0; i < users.length; i++){
             User user = user[i];
             if(id == user.getId()){
                 return user;
             }
        }
        throw new Resources.NotFoundException("User not found with id: "+id);
    }

}

因此,在您的活动中,您可以拥有:

 public void launch(Context c, int id) {
       Intent intent = User.getUser(id).getIntent();
       c.startActivity(intent);
 }

or something along those lines, you could extend this further and pass round 'User' objects instead of your raw id. You could also pass the context into the getIntent method and change it to a 'start' method. User is probably a bad name for this class I'm just unsure on your domain.

于 2012-06-17T21:14:13.280 回答