1

我正在使用数组适配器在列表视图中显示数组列表。我可以添加删除项目。假设如果列表视图中没有项目,如果我选择从绑定异常中删除其显示的索引。我需要的是它应该显示像“没有要删除的项目”这样的吐司。澄清我的专家!我的代码如下:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    bAdd = (Button) findViewById(R.id.button1);
    bDel = (Button) findViewById(R.id.button2);
    et1 = (EditText) findViewById(R.id.editText1);
    et2 = (EditText) findViewById(R.id.EditText2);
    et3 = (EditText) findViewById(R.id.EditText3);
    lv = (ListView) findViewById(R.id.listView1);

    al = new ArrayList<String>();
    aa = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_list_item_1, al);
    lv.setAdapter(aa);

    bAdd.setOnClickListener(new android.view.View.OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            String str1 = et1.getText().toString();
            if (str1.equals("")) {
                Toast.makeText(getApplicationContext(),
                        "Please Enter Item first!!", 0).show();
            } else {
                al.add(0, str1);
                aa.notifyDataSetChanged();
                et1.setText("");
            }

        }
    });
    bDel.setOnClickListener(new android.view.View.OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            if (arg0 == null) {
                Toast.makeText(getApplicationContext(),
                        "Nothing to delete", 0).show();
            } else {
                al.remove(0);
                aa.notifyDataSetChanged();
            }
        }
    });
4

2 回答 2

4

只需al在删除之前检查列表的大小:

        if (arg0 == null || al.isEmpty()) {
            Toast.makeText(getApplicationContext(),
                    "Nothing to delete", 0).show();
        } else {
            al.remove(0);
            aa.notifyDataSetChanged();
        }
于 2012-10-19T13:48:27.243 回答
1

在数组上设置验证,见下文

bDel.setOnClickListener(new android.view.View.OnClickListener() {

    public void onClick(View arg0) {
        // TODO Auto-generated method stub

        if (arg0 == null) {
            Toast.makeText(getApplicationContext(),
                    "Nothing to delete", 0).show();
        } else {
            if(al.size == 0){
             Toast.makeText(getApplicationContext(),
                    "There is no item to delete", 0).show();
               return;
             }
            al.remove(0);
            aa.notifyDataSetChanged();
        }
    }
});
于 2012-10-19T13:50:32.740 回答