调用具有“Activity”作为参数的函数

时间:2010-04-07 03:58:14

标签: android android-activity

为了简单起见,我已经删除了我的功能:

public static int countLines(String fileName, Activity activity) throws IOException {  
   BufferedReader in = new BufferedReader(new InputStreamReader(activity.getAssets().open(fileName))); 
   return 3;
}

我是从这里打电话的:

private CharSequence RandomRead() throws IOException {
    int numberLines = countLines("data.txt", ??????);           
    return "Success"
}

在对countLines(“data.txt”,??????)的调用中,我将什么作为Activity的参数?我已经用Google搜索了一整夜,我找不到实际调用Activity的例子,其中Activity是一个参数。 (很多例子实际上使用'活动',但没有调用示例函数。)

谢谢!

1 个答案:

答案 0 :(得分:1)

getAssets()是Context类中的一个函数。你可以使用Activity的原因是因为Activity是Context的间接子类。

根据您调用countLines的位置,您应该能够传递应用程序的上下文而不是活动对象。在大多数情况下,您可以通过调用getApplicationContext()来获取应用程序的上下文。只需将您的功能更改为:

public static int countLines(String fileName, Context context) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(context.getAssets().open(fileName))); 

return 3;
}