0

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

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()会收到一条错误消息,并提供一种快速修复方法 - create 方法getFilesDir()。这是因为它在一个扩展 View 的类中,我可以通过将方法放在 Activity 类中并通过使用静态在 View 类中使用该方法来解决这个问题。这不起作用,程序崩溃并且分数不会被保存。

4

2 回答 2

4

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

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

所以像这样的东西......

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

然后在你的活动中

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;
   }
}
于 2011-11-12T21:14:34.420 回答
3

使用 getContext 方法

 getContext().getFilesDir();
于 2011-11-12T21:17:12.110 回答