2012-06-17 49 views
0

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

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,这会很麻烦。有什么办法可以解决这个问题吗?

回答

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

或沿着这些线路的东西,你会这样进一步扩展,并通过圆“User”的对象,而不是你的原始ID。您也可以将上下文传递给getIntent方法,并将其更改为'start'方法。 User可能是该课程的一个糟糕名称,我只能确定您的网域。