我有一个listview,它显示存储在手机内部存储器中的文件列表(不带文件扩展名)。那我就要实施 OnItemLongClickListener
允许用户删除文件。 OnItemLongClickListener
使用“switch”语句。
因为每次删除一个文件时,列表视图中项目的位置都会改变,所以我想实现一个规则,检查文件名是否与相关文件匹配,无论在案例0、案例1等中是否移动文件名。
需要说明的是:
初始列表视图:
switch Listview items related file to delete
case 0; A A.map
case 1; B B.map
case 2; C C.map
case 3; D D.map
删除b后的listview:
switch Listview items related file to delete
case 0; A A.map
case 1; C C.map
case 2; D
现在,如果之前我在案例1中写了一个删除b.map的规则,它可以正常工作。但现在c项的规则与案例1相同,规则不匹配。
因为我是android新手,我不知道如何解决这个问题。
有人能帮我吗?
这就是活动
public class MainActivity extends Activity {
ListView lv;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/");
File[] filelist = dir.listFiles();
String[] theNamesOfFiles = new String[filelist.length];
for (int i = 0; i < theNamesOfFiles.length; i++) {
String temp = filelist[i].getName();
theNamesOfFiles[i] = temp.substring(0, temp.lastIndexOf('.'));
}
Arrays.sort(theNamesOfFiles);
adapter = new ArrayAdapter<String>(this, R.layout.list_row, theNamesOfFiles);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
// setting onItemLongClickListener and passing the position to the function
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
switch(position){
case 0:{
}
break;
case 1:{
}
break;
case 2:{
}
break;
case 3:{
}
break;
case 4:{
}
break;
}
return true;
}
});
}
public void doDeleteFile(int position){
File fileToDelete = new File(Environment.getExternalStorageDirectory().getPath() + "/osmdroid/tiles/", "A.map");
if(!fileToDelete.isDirectory()){
try{
if(fileToDelete.delete()){
System.out.println("File delete operation success");
}
else{
System.out.println("File delete operation failed");
}
}catch(Exception ex){
System.out.println("Exception :"+ex.getMessage());
}
}else{
System.out.println("It is not a file");
}
}
}
2条答案
按热度按时间zysjyyx41#
我会这样做:
首先,我将有一个关于项目的数据结构。
adapter = new ArrayAdapter(this, R.layout.list_row, arrayOfMyFileObjects);
MyFile item = adapter.getItem(position);
public class MainActivity extends Activity {
ListView lv;
ArrayAdapter adapter;
public void list() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
}
public void doDeleteFile(File fileToDelete) {
if (!fileToDelete.isDirectory()) {
}
public class MyFile {
File file;
String fileName;
}
ggazkfy82#
删除项目时,也将其从数组中删除,然后在更新数组项目后在适配器上调用notifydatasetchange()
不需要查名字。你可以按职位来做