我正在创建一个歌词应用程序,我需要一些帮助来编写我需要的下一个进程。 我创建了一个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,android.R.layout.simple_list_item_1,titles);
listView.setAdapter(adapter);
}
}
现在,下一步是创建一个OnItemClickListener并让我们说 如果&#34;惊人的恩典&#34;从列表中选出, 它将查找与String中定义的名称相同的文件。 例如:&#34; Amazing Grace.xml&#34; //即使包含空格
所以逻辑就像:打开文件位置/&#34;被选中的标题&#34; .xml
我无法使用&#34; case&#34;因为我将创建许多歌曲标题,并在我更新应用程序时添加更多。 感谢阅读,我真的很感激任何帮助;)
答案 0 :(得分:0)
你应该映射你的歌词,所以当你用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);
//..
以下是如何使用OnItemClickListener的示例:
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);
P.S我假设您没有处理数据库项目,否则您应该使用id
而不是pos
值。
答案 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"