【问题标题】:How to modify the name of the class (variable instead of hardcoded) in Intent?如何在 Intent 中修改类的名称(变量而不是硬编码)?
【发布时间】:2018-01-14 17:57:49
【问题描述】:
final Button voteYes = (Button) findViewById(R.id.voteYes);

    voteYes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                Intent successPhase = new Intent(player1.this, player5.class);
                startActivity(successPhase);

        }
    });

我有一个整数变量,范围从 1 到 5,表示整数。所以,我的问题是,如果我希望它是 player[number].class 而不是固定的“player5.class”,我该怎么办? (而不是硬编码的“5”,我希望它是“数字”)

【问题讨论】:

    标签: java android string class android-intent


    【解决方案1】:

    例如可以做如下的事情:

    Intent intent = new Intent();
    String myClassName = "player" + number; // use full package of class 
    intent.setClassName(context, myClassname;
    startActivity(intent);
    

    【讨论】:

    • Intent inGame = new Intent();字符串领导者 = "player3"; inGame.setClassName(MainActivity.this, leader);开始活动(游戏内);当我点击按钮时,应用程序崩溃,而上述工作正常。
    • 对不起,我忘了使用全包类。感谢您的帮助!
    【解决方案2】:
    Class players [] = {Player1.class, Player2.class,Player3.class, Player4.class,Player5.class};
    

    这样使用:

    Intent successPhase = new Intent(this, players[number]);
                    startActivity(successPhase);
    

    【讨论】:

      猜你喜欢
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      相关资源
      最近更新 更多