在我的应用中,文件名等信息存储在外部存储中。然后在ListView的帮助下将它们实现到应用程序中。我可以使用OnItemLongClickListener()单独删除文件,但我想在ListView中选择多个文件,然后单击“删除”按钮。我怎样才能做到这一点?我的MainActivity文件如下:
public class MainActivity extends AppCompatActivity {
ArrayList<FileName> filenames;
ListViewAdapter adapter;
ListView lv_filenames;
public Handler handler;
private String _path = Environment.getExternalStorageDirectory() + "/sample_directory/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditorManager manager = new EditorManager(getApplicationContext());
manager.CreateNewDirectory();
lv_filenames = (ListView) findViewById(R.id.list);
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
filenames = manager.GetList();
adapter = new ListViewAdapter(getApplicationContext(), R.layout.listView, filenames);
lv_filenames.setAdapter(adapter);
lv_filenames.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int file_name, long l) {
final File deleteFile = new File(_path + filenames.get(file_name).getName());
final String tempFileName = filenames.get(file_name).getName() + " is deleted";
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Delete File");
builder.setMessage("Do you really want to delete this file?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
boolean deleted = deleteFile.delete();
if (deleted) {
Toast.makeText(getApplicationContext(), tempFileName, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Do nothing.
}
});
builder.create();
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
});
}
}
我删除了额外的代码。 Thanx帮忙!
PS -
我听说在Android 4.4 +文件中不能像这样删除。我该怎么办?
编辑 -
我看到了那些答案。但我想创建一个按钮,单击其上的检查/取消选中按钮。我怎样才能做到这一点?我希望只有在单击“删除”按钮时才能看到“检查/取消选中”按钮。其他答案也有点令人困惑。
答案 0 :(得分:0)
我会有一个带有编辑或删除图标的按钮,并将ListView更改为每个视图中带有复选框的ListView。要么使用新的Adapter创建一个新的ListView,要么告诉适配器并在其中设置一个布尔值,然后dataSetChange适配器。
答案 1 :(得分:0)
我解决了我的问题。我使用SparseBooleanAdapter来注册删除选项。然后我按删除按钮删除它们。