【问题标题】:Is it possible to use an intent in a class which extends a view?是否可以在扩展视图的类中使用意图?
【发布时间】:2013-01-08 17:58:09
【问题描述】:

我正在为 Android 制作一款回合制 RPG 游戏。我有一个扩展视图的类,我需要启动另一个也扩展视图的类。第一类是玩家在地图上走动的地方,第二类是战斗画面。我试图让它工作,但我得到了这个错误。

The constructor Intent(GameView, Class<BattleView>) is undefined

我之前使用过意图完全没有任何问题,但我从未尝试在扩展视图的类中使用意图。我想这就是我遇到问题的原因。 是否可以在扩展视图的类中使用意图?

有什么想法吗?

【问题讨论】:

    标签: android class android-intent view


    【解决方案1】:

    您正在寻找的Intent 的构造函数需要一个上下文,然后是您要启动的类(一个活动)。

    从您的视图类中,您应该能够做到这一点:

    Intent intentToLaunch = new Intent(getContext(), BattleView.class);
    

    这将正确创建您的 Intent,但您将无法从您的视图中启动 Activity,除非您将 Activity 传递给您的视图,这是一个非常糟糕的主意。确实这是一个糟糕的设计,因为您的视图不应该启动其他活动。相反,您的视图应该调用该视图的创建者将响应的接口。

    它可能看起来像这样:

    public class GameView extends View {
    
      public interface GameViewInterface {
        void onEnterBattlefield();
    
      }
      private GameViewInterface mGameViewInterface;
      public GameView(Context context, GameViewInterface gameViewCallbacks) {
          super(context);
          mGameViewInterface = gameViewCallbacks;
      }
    
      //I have no idea where you are determining that they've entered the battlefield but lets pretend it's in the draw method
      @Override
      public void draw(Canvas canvas) {
    
         if (theyEnteredTheBattlefield) {
           mGameViewInterface.onEnterBattlefield();
         } 
      }
    
    }
    

    现在您很可能是从 Activity 类创建此视图,因此在该类中,只需创建 GameViewInterface 的实例。当您在 Activity 中调用 onEnterBattlefield() 时,按照我向您展示的意图调用 startActivity。

    【讨论】:

    • 非常感谢!这正是我所需要的。
    猜你喜欢
    • 2013-10-02
    • 2014-02-04
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多