从ListView中选择项目并将其删除onClick - Android待办事项列表应用程序

时间:2014-05-10 22:18:48

标签: java android android-listview

我对Android Dev / Java非常陌生,我正在线上学习并尝试为Android创建一个简单的待办事项列表应用程序。看起来教程有点过时,依赖于DPAD在任务列表中上下导航,以便定位列表项并使用"删除按钮"删除它。在应用程序菜单中。我正在努力弄清楚如何选择"点击列表项并使用"删除"删除它按钮。现在当单击列表项时它什么都不做,所以当我单击删除按钮时,应用程序不知道选择了哪个。这是我的XML和Java代码。任何见解都会非常有用。

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/textItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textItem"
        android:layout_below="@+id/textItem"
        android:text="@string/add" />

    <ListView
        android:id="@+id/listItems"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnAdd"
        android:layout_alignRight="@+id/btnAdd"
        android:layout_below="@+id/btnAdd"
        android:layout_marginTop="20dp" >
    </ListView>
</RelativeLayout>

JAVA

    package com.example.todo;

import java.util.ArrayList;  
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle; 
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener, DialogInterface.OnClickListener, OnKeyListener {

    EditText textItem;
    Button btnAdd;
    Button btnDelete;
    ListView listItems;

    ArrayList<String> toDoItems;
    ArrayAdapter<String> aa;

    String[] date = {"Movie", "Dinner", "Drinks"};
    String[] gym = {"Cardio", "Upper Body", "Lower Body"};
    String[] meeting = {"30min Meeting", "1 Hour Meeting", "2 Hour Meeting"};
    String[] homework = {"Paper", "Exercise", "Assignment"};
    String[] project = {"App", "Web", "Graphic Design"};
    String currentMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textItem = (EditText)findViewById(R.id.textItem);
        btnAdd = (Button)findViewById(R.id.btnAdd);
        btnDelete = (Button)findViewById(R.id.btnDelete);
        listItems = (ListView)findViewById(R.id.listItems);

        btnAdd.setOnClickListener(this);
        textItem.setOnKeyListener(this);

        toDoItems = new ArrayList<String>();
        aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, toDoItems);
        listItems.setAdapter(aa);

        /*--Set heading to todays Date--*/
            TextView tvDisplayDate = (TextView) findViewById(R.id.heading);
            final Calendar c = Calendar.getInstance();
            int yy = c.get(Calendar.YEAR);
            int mm = c.get(Calendar.MONTH);
            int dd = c.get(Calendar.DAY_OF_MONTH);

            // set current date into textview
            tvDisplayDate.setText(new StringBuilder()
            // Month is 0 based, just add 1
            .append(mm + 1).append("/").append(dd).append("/").append(yy));

    }

    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuItem item;
        item = menu.add("delete");
        item.setIcon(R.drawable.remove);
        item = menu.add("date");
        item.setIcon(R.drawable.date);
        item = menu.add("gym");
        item.setIcon(R.drawable.gym);
        item = menu.add("meeting");
        item.setIcon(R.drawable.meeting);
        item = menu.add("homework");
        item.setIcon(R.drawable.homework);
        item = menu.add("project");
        item.setIcon(R.drawable.project);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        if (item.hasSubMenu() == false) {
            if (item.getTitle() == "date") {
                currentMenu = "date";
                this.displayPopup("Date Options", this.date);
            }
            if (item.getTitle() == "gym") {
                currentMenu = "gym";
                this.displayPopup("Gym Options", this.gym);
            }
            if (item.getTitle() == "meeting") {
                currentMenu = "meeting";
                this.displayPopup("Meeting Options", this.meeting);
            }
            if (item.getTitle() == "homework") {
                currentMenu = "homework";
                this.displayPopup("Homework Options", this.homework);
            }
            if (item.getTitle() == "project") {
                currentMenu = "project";
                this.displayPopup("Project Options", this.project);
            }
            if(item.getTitle() == "delete") {
                int index = listItems.getSelectedItemPosition();
                this.deleteItem(index);
            }
        }
        return true;
    }

    private void addItem(String item) { 
        if (item.length() > 0 ) { 
            Toast.makeText(getApplicationContext(), item+" added", Toast.LENGTH_SHORT).show();
            this.toDoItems.add(item);
            this.aa.notifyDataSetChanged();
            this.textItem.setText("");
        }
    }

    private void deleteItem(int itemId) {
        if (itemId >=0) {
            String itemName = (String)listItems.getItemAtPosition(itemId);
            Toast.makeText(getApplicationContext(), itemName+" delete", Toast.LENGTH_SHORT).show();
            this.toDoItems.remove(itemId);
            aa.notifyDataSetChanged();
        }
    }

    private void displayPopup(String title, String[] items) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setItems(items, this);
        builder.show();
    }

    @Override
    public void onClick(View v) {
        if (v == this.btnAdd) { 
            this.addItem(this.textItem.getText().toString());
        }
    }


    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 
            this.addItem(this.textItem.getText().toString());
        }
        return false;
    }

    @Override
    public void onClick(DialogInterface dialog, int item) {
        if (currentMenu == "date") this.addItem(date[item]);
        if (currentMenu == "gym") this.addItem(gym[item]);
        if (currentMenu == "meeting") this.addItem(meeting[item]);
        if (currentMenu == "homework") this.addItem(homework[item]);
        if (currentMenu == "project") this.addItem(project[item]);


    listItems.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
            listItems.setSelection(position);
            view.setSelected(true); 
        }
    });}
}

3 个答案:

答案 0 :(得分:1)

我看到它的方式,你必须选择,你必须使用onItemClick:

第一个是点击它时删除项目

listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // remove the item from the array
        toDoItems.remove(position);
        // call a UI update for the list
        aa.notifyDataSetChanged();
    }
});

第二个是存储点击的项目位置,然后在用户点击菜单中的删除按钮后调用删除操作。

int selectedItem = -1;
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //save the clicked item position 
        // and the when the delete button is pressed, use it.
        // keep in mind that this is not that good if you are using recycled list
        selectedItem = position;            }
});

无论如何,我建议先开始使用更新的教程......

答案 1 :(得分:0)

从ListActicity扩展并覆盖onListItemClicked方法。

答案 2 :(得分:0)

选择并点击是两件不同的事情。

覆盖listview.setOnItemClickListener并设置所选的单击列表项。然后你的删除工作。

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
        listview.setSelection(position);
        view.setSelected(true); 
    }
});

您应该尝试使用本教程来了解有关listview的更多信息: http://www.vogella.com/tutorials/AndroidListView/article.html