有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何打开与字符串中定义的名称相同的文件?

我正在创建一个抒情应用程序,我需要一些帮助来编写我需要的下一个过程。 我创建了一个ListView并在上面添加了一些字符串

public class MainActivity extends AppCompatActivity {

String titles[] = new String [] {"Amazing Grace", "How Great Thou Art", 
"King of All Kings", "What A Beautiful Name"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView listView =(ListView) findViewById(R.id.titlelist);
    ArrayAdapter<String> adapter=new ArrayAdapter<String> 
    (this,安卓.R.layout.simple_list_item_1,titles);
    listView.setAdapter(adapter);
 }
}

现在下一步是创建一个监听器 如果从列表中选择“惊人的优雅”, 它将查找与字符串中定义的名称相同的文件。 例如:“惊人的Grace.xml”//即使包含空格

因此,逻辑将类似于:openfilelocation/“title that selected”。xml

我不能使用“case”,因为我将创建很多歌曲标题,并在更新应用程序时添加更多内容。 感谢您的阅读,我非常感谢您的帮助;)


共 (2) 个答案

  1. # 1 楼答案

    要打开文件,请执行以下操作:

    int selected = 0; // set selected to index of what is selected
    File file = new File(Environment.getExternalStorageDirectory(), //folder location where you store the files
    titles[selected]+".xml"); //in case of xml files. If other types, you'll need to add case for diff types
    Uri path = Uri.fromFile(file);
    Intent fileOpenintent = new Intent(Intent.ACTION_VIEW);
    fileOpenintent .setDataAndType(path, "application/xml"); //for xml MIME types are text/xml and application/xml
    try {
        startActivity(fileOpenintent);
    }
    catch (ActivityNotFoundException e) {
    
    }
    

    正如您所解释的,您最大的问题是如何处理多个文件名。这就是代码的这一部分:titles[selected]+".xml"

  2. # 2 楼答案

    你应该映射你的歌词,这样当你点击带有pos = 5的条目时,你就会知道哪个条目的ps与哪个文件(或xml)相关

    以下是如何使用文件名映射ID的示例:

    HashMap<String,Strin> lyricsMap = new HashMap<>();
    lyricsMap(0, R.raw.song_lyric0);
    lyricsMap(1, R.raw.song_lyric1);
    lyricsMap(2, R.raw.song_lyric2);
    lyricsMap(3, R.raw.song_lyric3);
    lyricsMap(4, R.raw.song_lyric4);
    lyricsMap(5, R.raw.song_lyric5);
    lyricsMap(6, R.raw.song_lyric6);
    //..
    

    以下是如何使用McClickListener的示例:

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
            int rawResId = lyricsMap.get(pos);
    
            //here comes the method for returning lyrics for file by it's resource id
    
            //...
        }
    };
    adapter.setOnItemClickListener(onItemClickListener);
    

    另外,我假设您没有处理数据库项,否则应该使用id而不是pos