简体   繁体   English

无法从类方法启动活动

[英]Trouble launching activity from class method

I'm new to Java and Android Studio, and to learn I'm building a character generator app for Dungeons and Dragons. 我是Java和Android Studio的新手,并且我正在为Dungeons and Dragons构建一个角色生成器应用程序。 You choose a race, character class, and skills, then the app calculates everything and builds a final character sheet. 您选择种族,角色类和技能,然后应用程序计算所有内容并构建最终的角色表。

I have an activity that allows the user to select a class (fighter, wizard, etc.) from a list. 我有一个活动允许用户从列表中选择一个类(战斗机,向导等)。 It then stores the selection in a SharedPreferences File. 然后,它将选择存储在SharedPreferences文件中。

I want to call different sub activities for different classes. 我想为不同的类调用不同的子活动。 In these activities, a selection is made and is written to the SharedPreferences File. 在这些活动中,将进行选择并将其写入SharedPreferences文件。 For example, a fighter gets to choose a fighting style while a wizard gets to choose spells. 例如,当巫师选择法术时,战士可以选择战斗风格。

Right now I have a (java)class for the fighter class, and one for the wizard class. 现在我有一个(java)类用于战斗机类,一个用于向导类。 Both have a public void create() method. 两者都有一个public void create()方法。

Calling the method: 调用方法:

if (chosenClass.equalsIgnoreCase("fighter")){
            Fighter classObject = new Fighter();
            Fighter.create();
        }

Here is the code from the Fighter class: 以下是Fighter类的代码:

import android.content.Intent;

public class Fighter {

    public Fighter(){}

    public void create(){
        Intent fightingStyle = new Intent(this, ChooseFightingStyle.class);
        startActivity(fightingStyle);
    }  
}

However, I'm getting an error message saying "Cannot resolve constructor 'Intent(...)' 但是,我收到一条错误消息“无法解析构造函数'Intent(...)'

Can anyone give me some insight on what I'm doing wrong? 任何人都能给我一些关于我做错了什么的见解吗? Or suggestions on how to do this better? 或者建议如何更好地做到这一点? Thanks so much. 非常感谢。

That's because "this" in your case does not represent a Context, you should try something like this: 那是因为在你的情况下“this”并不代表一个Context,你应该尝试这样的事情:

public void create(Context context){
    Intent fightingStyle = new Intent(context, ChooseFightingStyle.class);
    startActivity(fightingStyle);
} 

As per documentation of Intent class constructors, they can take a string as first argument or a Context. 根据Intent类构造函数的文档,它们可以将字符串作为第一个参数或Context。 Your Fighter class should be of type Context to pass it as argument. 您的Fighter类应该是Context类型,以将其作为参数传递。 However, if you have a reference to the context, you can pass it too in the Intent constructor. 但是,如果您具有对上下文的引用,则也可以在Intent构造函数中传递它。

A suggestion: when you select the Fighter class from the list in the main activity, you can pass the context from the main activity. 建议:当您从主活动的列表中选择Fighter类时,您可以从主活动传递上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM