我是 android 新手,我在我的代码中使用 ListView。我的代码如下:
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.content.DialogInterface;
@SuppressLint("NewApi")
public class MainActivity extends Activity
{
int counter;
ListView listView;
ArrayAdapter <String> adapter;
Button btnAddAgain, btnDeleteSelected;
ArrayList <String>listItems=new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter=0;
listView=(ListView) findViewById(R.id.myList);
adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,listItems);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
btnAddAgain=(Button) findViewById(R.id.addAgain);
btnAddAgain.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
listItems.add("Clicked " +counter++);
adapter.notifyDataSetChanged();
}
});
btnDeleteSelected=(Button) findViewById(R.id.btnDelete);
btnDeleteSelected.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Delete?");
builder.setTitle("Confirm Action");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < listItems.size(); i++)
{
if (checked.get(i)==true)
{
listItems.remove(i);
adapter.notifyDataSetChanged();
}
}
//checked.clear();
}
});
builder.setNegativeButton("Cancel", null);
builder.create();
builder.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
但删除按钮仅删除 ListView 的第一个元素。有人请帮助我。我正在尝试自己学习android。你的帮助对我学习安卓很有帮助。我在代码中做了哪些更改以从列表中删除选中的项目。多谢你们