1

我正在开发一个 Android 应用程序,但我遇到了一个小问题。我在assets文件夹中有一个html文件列表,所有文件都根据国家名称命名,例如“United Kingdom.html”,我让用户从列表视图中选择国家名称,我从列表中获取国家名称并将其保存为名为“country_name”的字符串,然后将其作为“值”字符串传递给不同的活动。我正在尝试提出一个解决方案,基本上检查资产文件夹中是否存在同名文件,如果存在,则使用 webview 打开该文件。下面的代码是我到目前为止所得到的。

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String value = extras.getString("country_name");
        result_info = (TextView) findViewById(R.id.result_info);
        result_info.setText(value);
        try {
            Arrays.asList(getResources().getAssets().list("")).contains(value);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        webview = (WebView) findViewById(R.id.webview);
        webview.loadUrl("file:///android_asset/United Kingdom.html");
}

提前致谢。


编辑:我可能已经找到了一个可能的解决方案。基本上将文件名列表作为字符串数组获取,然后将其与我的字符串(“value”+“.html”)进行比较。

final AssetManager assetManager = getAssets();
    try {
        // for assets folder add empty string
                    String[] filelist = assetManager.list("");
                    // for assets/subFolderInAssets add only subfolder name
                    String[] filelistInSubfolder = assetManager.list("subFolderInAssets");
        if (filelist == null) {
            // dir does not exist or is not a directory
        } else {
            for (int i=0; i<filelist.length; i++) {
                // Get filename of file or directory
                String filename = filelist[i];
            }
        }

                    // if(filelistInSubfolder == null) ............  

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

编辑 2:解决方案

感谢 Venkatesh,我让它工作了。他的解决方案几乎不需要更改,但我最终通过以下代码使其工作:

        AssetManager am = getAssets();
        String extension = ".html";
        try {
            String fileList[] = am.list("");
            //checking if any file gets returned from the array
            //result_info.setText(fileList[1]);
            for (String fileName : fileList) {

                  if (fileName.equals(value+extension)) {  
                      //checking what the filename looks like 
                      //result_info.setText(fileName);
                      webview = (WebView) findViewById(R.id.webview);
                      webview.loadUrl("file:///android_asset/"+fileName);
                   }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
4

1 回答 1

0

尝试这个,

AssetManager am = getAssets();
String fileList[] = am.list("");

 for (String fileName : fileList) {

  if (fileName.equals(value+"addExtensions")) {  
     webview.loadUrl("file:///android_asset/"+filename);
   }
}
于 2013-11-18T07:14:32.847 回答