如何在添加和编辑listview项目时使用自定义适配器?

时间:2013-11-12 15:12:25

标签: java android android-listview android-custom-view android-adapter

我想实现一个待办事项列表应用程序。我有三个活动:一个主要活动,一个添加活动和一个编辑活动。在我的主要活动中,有一个添加按钮和一个列表视图,显示待办事项。单击“添加”按钮时,将执行添加活动。在此活动中,有一个任务的edittext,一个datepicker和一个优先级的微调器。单击“确定”按钮时,所有这些所需的值将作为一行发送到主要活动的列表视图。并且,当单击此列表上的项目时,将执行编辑活动,用户可以更改值。但是,在我的代码中,当用户输入值时,我可以在我的自定义适配器类中访问它们,但我无法在列表视图中显示它们。 Listview仍然是空的。我该如何修复我的代码?

主要活动:

public class MainActivity extends Activity {

protected static final String edits = "mainTask";

private ToDoItemAdapter listAdapter;
//private ToDoItemAdapter myCustomAdapter;
//private ArrayList<String> listString;
public ArrayList<ToDoItem> listItems;

public static final int ADD_TASKS = 1;
public static final int EDIT_TASKS = 2;

Button button;
ListView listView;

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

@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;
}

private void initUI() {

    getViewReferences();
    initializeToDoList();

}

private void setListener() {
    // TODO Auto-generated method stub
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent addTaskIntent = new Intent(MainActivity.this, AddActivity.class);
            startActivityForResult(addTaskIntent, ADD_TASKS);
        }
    });

    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            System.out.println(arg2);
            ToDoItemAdapter myAdapter = new ToDoItemAdapter(MainActivity.this,R.layout.editing_task,listItems);
            listView.setAdapter(myAdapter);
            Intent editTaskIntent = new Intent(MainActivity.this, EditingTask.class);
            //editTaskIntent.putExtra("mainTask", arg2);
            startActivityForResult(editTaskIntent, EDIT_TASKS);
        }
    });

}

private void getViewReferences() {
    // TODO Auto-generated method stub
    button = (Button) findViewById(R.id.addButton);
    listView = (ListView) findViewById(R.id.listView);
}


private void initializeToDoList() {
    // TODO Auto-generated method stub
    listItems = new ArrayList<ToDoItem>();
    //listString = new ArrayList<String>();
    listAdapter = new ToDoItemAdapter(MainActivity.this, R.layout.activity_main, listItems);
    listView.setAdapter(listAdapter);

    View noTaskView = findViewById(R.id.emptyToDoList);
    listView.setEmptyView(noTaskView);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
        case ADD_TASKS:
            updateToDoList(data);
            break;
        case EDIT_TASKS:
            break;
        default:
            break;
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}

private void updateToDoList(Intent data) {
    // TODO Auto-generated method stub
    String task = AddActivity.tasks;
    ArrayList<String> list = data.getStringArrayListExtra(task);
    String addedTask = list.get(0);
    String addedDeadline = list.get(1);
    String addedPriority = list.get(2);
    ToDoItem item = new ToDoItem(addedTask, addedDeadline ,"0", addedPriority);
    listItems.add(item);
    //listString.add(addedTask + "   " + addedDeadline + "   " + addedPriority);
    Log.w("Items:",listItems.get(0).getTask());
    //Log.w("String:",listString.get(0));
    listAdapter.notifyDataSetChanged();
}

}

ToDoItemAdapter类:

public class ToDoItemAdapter extends ArrayAdapter<ToDoItem> { 

    Context context;
    private int resource; 
    ArrayList<ToDoItem> todoItem;

    public ToDoItemAdapter(Context context, int resource, ArrayList<ToDoItem> objects) { 

        super(context, resource, objects); 
        this.context = context;
        this.resource = resource;
        this.todoItem = objects;
    } 

    @Override
        public ToDoItem getItem(int position) {
        return this.todoItem.get(position);
    }

    @Override
        public int getCount() {
        return this.todoItem.size();
    }

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
        // TODO Auto-generated method stub 

        View row = convertView;

        if (convertView == null) 
        { 
            /*todoView = new LinearLayout(getContext()); 
            String inflater = Context.LAYOUT_INFLATER_SERVICE; 
            LayoutInflater li; 
            li = (LayoutInflater)getContext().getSystemService(inflater); 
            li.inflate(resource, todoView, true); 
            */

            LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(resource, parent, false);
        } 


        //LinearLayout todoView; 
        ToDoItem todo = getItem(position); 
        String taskString = todo.getTask(); 
        Log.w("task:", taskString);
        String dateString = todo.getDeadline(); 
        String priorityString = todo.getPriority(); 
        String itemRow = taskString + "   " + dateString + "   " + priorityString;

        return row; 
    } 
}

添加课程:

public class AddActivity extends Activity{


    private String[] states;
    private Spinner spinner;
    int position1;
    String priority;

    EditText etDate;
    Button change_date;
    final int Date_Dialog_ID=0;
    int cDay,cMonth,cYear; // this is the instances of the current date
    Calendar cDate;
    int sDay,sMonth,sYear; // this is the instances of the entered date

    protected static final String tasks = "addingTask";
    private static final String LOG_TAG = "addingTaskActivity";

    MainActivity main;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        initUI();
        showDatePicker();
        showPriorityLevel();
    }

    private void showPriorityLevel() {
        // TODO Auto-generated method stub
        states = getResources().getStringArray(R.array.priority_level);
        spinner = (Spinner) findViewById(R.id.priority_spinner);

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, states);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);

        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {

                position1 = spinner.getSelectedItemPosition();

                switch(position1)
                {
                    case 0: priority = "0";
                            break;
                    case 1: priority = "1";
                            break;
                    case 2: priority = "2";
                            break;
                    case 3: priority = "3";
                            break;
                    case 4: priority = "4";
                            break;
                    case 5: priority = "5";
                            break;
                    case 6: priority = "6";
                            break;
                    case 7: priority = "7";
                            break;
                    case 8: priority = "8";
                            break;
                    case 9: priority = "9";
                            break;
                    default: break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });
    }


    private void showDatePicker() {
        // TODO Auto-generated method stub

        etDate=(EditText)findViewById(R.id.EditText01);
        change_date=(Button)findViewById(R.id.Button01);
        change_date.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
        // TODO Auto-generated method stub
        //triggers the DatePickerDialog
        showDialog(Date_Dialog_ID);
        }
        });
        //getting current date
        cDate=Calendar.getInstance();
        cDay=cDate.get(Calendar.DAY_OF_MONTH);
        cMonth=cDate.get(Calendar.MONTH);
        cYear=cDate.get(Calendar.YEAR);
        //assigning the edittext with the current date in the beginning
        sDay=cDay;
        sMonth=cMonth;
        sYear=cYear;
        updateDateDisplay(sYear,sMonth,sDay);

    }

    @Override
    protected Dialog onCreateDialog(int id) {

    switch (id) {
    case Date_Dialog_ID:
    return new DatePickerDialog(this, onDateSet, cYear, cMonth,
    cDay);
    }
    return null;
    }

    private void updateDateDisplay(int year,int month,int date) {
    // TODO Auto-generated method stub
    etDate.setText(date+"-"+(month+1)+"-"+year);
    }

    private OnDateSetListener onDateSet=new OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            sYear=year;
            sMonth=monthOfYear;
            sDay=dayOfMonth;
            updateDateDisplay(sYear,sMonth,sDay);
        }
    };

    private void initUI() {
        // TODO Auto-generated method stub
        setContentView(R.layout.adding_task);

        final EditText editTextTask = (EditText) findViewById(R.id.edit_text_task);
        Button OKbutton = (Button) findViewById(R.id.ok_Button);
        final EditText editTextDate = (EditText) findViewById(R.id.EditText01);

        OKbutton.setOnClickListener(new OnClickListener() {


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

                ArrayList<String> addedDatas = new ArrayList<String>();

                String addingTask = editTextTask.getText().toString();

                String deadline = editTextDate.getText().toString();

                //String concatenate = priority + "   " + addingTask + "   " +  deadline;

                Intent myIntent = new Intent();

                addedDatas.add(addingTask);
                addedDatas.add(deadline);
                addedDatas.add(priority);

                myIntent.putExtra("addingTask", addedDatas);

                setResult(Activity.RESULT_OK, myIntent);

                finish();
            }
        });
    }

}

ToDoItem类

public class ToDoItem {

    String task;
    String deadline;
    String status;
    String priority;

    public ToDoItem(String task, String deadline, String status, String priority) {
        super();
        this.task = task;
        this.deadline = deadline;
        this.status = status;
        this.priority = priority;
    }

    public String getTask() {
        return task;
    }

    public String getDeadline() {
        return deadline;
    }

    public String getStatus() {
        return status;
    }

    public String getPriority() {
        return priority;
    }

    @Override
    public String toString() {

        return priority +  "   " + task + "   " + deadline + "   " + status;
    }

1 个答案:

答案 0 :(得分:0)

您应该做的是确保添加活动可以访问用于在主活动中填充ListView的ToDoItem数组。然后它可以直接添加或修改此列表。然后,您可以在MainActivity的onStart()中调用notifyAdapters(),以便在可见时检查更新。