gpt4 book ai didi

java - getFilesDir() 在子类中查看

转载 作者:行者123 更新时间:2023-12-01 07:38:45 25 4
gpt4 key购买 nike

我可以在使用 extends View 的 .class 中使用方法 getFilesDir() 吗?

public void save(){
try {
File myDir = new File(getFilesDir().getAbsolutePath());
FileWriter fw = new FileWriter(myDir + "/Test.txt");
fw.write(Integer.toString(score));
fw.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

仅方法 getFilesDir() 会收到错误消息,并提供一个快速修复方法 - 创建方法 getFilesDir()。这是因为它位于一个带有 extends View 的类中,我可以通过将该方法放入 Activity 类中并使用 static 来使用 View 类中的方法来解决此问题。这不起作用,程序崩溃并且分数无法保存。

最佳答案

只需将 Context 传递给您的 View 构造函数,您就可以获得 SD 卡的位置。

[编辑]我的意思是,你的这个扩展 View 的类可能不存在于任何可以本地访问上下文的地方,因此当你在 Activity 中实例化它时,你需要在构造函数 FROM 中传递该对象(你确实有对其的引用)。

所以像这样......

class Foo extends View{
public foo (Context c){
c.getFilesDir(); // or any method that belongs to context
}
}

然后在您的 Activity 中

class Main extends Activity{
@override
public void onCreate(){
super.onCreate();


Foo foo = new Foo(this); //this is a reference to the activity AND is also the context;
}
}

关于java - getFilesDir() 在子类中查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8107581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com