0

我有两个活动。一个是主要活动(一个添加按钮和一个列表视图),另一个是任务名称的编辑文本,日期的日期选择器,任务优先级的微调器。当我启动这个应用程序时,它会显示添加按钮,当我单击此按钮时,它会显示编辑文本、日期选择器和微调器,当我填写这些字段并单击确定按钮时,它会将其添加到 mainactivity 的列表视图中。我的代码提供了向列表视图添加新项目,但我对如何编辑这些项目感到困惑。当我单击列表视图中的一个项目时,我想创建新的编辑活动(此活动还必须具有编辑文本、微调器、日期选择器以及用户输入的值。)并且此活动更新/编辑主活动的项目列表显示。在我的代码中,当我单击列表视图中的一个项目时,我收到如下错误:

日志猫:

11-11 16:47:38.311: E/AndroidRuntime(1015): FATAL EXCEPTION: main
11-11 16:47:38.311: E/AndroidRuntime(1015): java.lang.ClassCastException: android.widget.Spinner cannot be cast to android.widget.TextView
11-11 16:47:38.311: E/AndroidRuntime(1015):     at com.example.enhancedtodolistapplication.ToDoItemAdapter.getView(ToDoItemAdapter.java:52)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.widget.AbsListView.obtainView(AbsListView.java:2177)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.widget.ListView.measureHeightOfChildren(ListView.java:1247)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.widget.ListView.onMeasure(ListView.java:1159)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.View.measure(View.java:15848)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.View.measure(View.java:15848)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.View.measure(View.java:15848)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:302)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.View.measure(View.java:15848)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5008)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.View.measure(View.java:15848)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.Choreographer.doCallbacks(Choreographer.java:562)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.Choreographer.doFrame(Choreographer.java:532)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.os.Handler.handleCallback(Handler.java:730)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.os.Looper.loop(Looper.java:137)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at java.lang.reflect.Method.invokeNative(Native Method)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at java.lang.reflect.Method.invoke(Method.java:525)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-11 16:47:38.311: E/AndroidRuntime(1015):     at dalvik.system.NativeStart.main(Native Method)

这是我的代码:

AddActivity.java

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();
        }
    });
}

}

MainActivity.java

public class MainActivity extends Activity {

protected static final String edits = "mainTask";

private ArrayAdapter<String> 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);
}

@SuppressWarnings({ "unchecked", "rawtypes" })
private void initializeToDoList() {
    // TODO Auto-generated method stub
    listItems = new ArrayList<ToDoItem>();
    listString = new ArrayList<String>();
    listAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, listString);
    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.java

公共类 ToDoItemAdapter 扩展 ArrayAdapter {

private int resource; 

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

    super(context, resource, objects); // TODO Auto-generated constructor stub 
    this.resource = resource;
} 

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

    LinearLayout todoView; 
    ToDoItem todo = getItem(position); 
    String taskString = todo.getTask(); 
    String dateString = todo.getDeadline(); 
    String priorityString = todo.getPriority(); 

    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); 
    } 
    else 
    { 
        todoView = (LinearLayout) convertView; 
    } 

    TextView taskView = (TextView) todoView.findViewById(R.id.edit_text_task2); 
    TextView dateView = (TextView) todoView.findViewById(R.id.EditText02); 
    TextView priorityView = (TextView) todoView.findViewById(R.id.priority_spinner2); 
    taskView.setText(taskString); 
    dateView.setText(dateString); 
    priorityView.setText(priorityString); 
    return todoView; 
} 

}

ToDoItem.java

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

}

最后我有一个 EditingTask.java 类,我不知道如何与我的自定义适配器结合使用......

先感谢您。

4

2 回答 2

0

要获得被点击的元素,您应该使用 OnItemClickListener。这是示例:

list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view,
                int position, long id) {

            MyAdapter adapter = (MyAdapter) list.getAdapter();

            String name = adapter.getItem(position).getName();

            Intent intent = new Intent(MainActivity.this, DetailActivity.class);
            intent.putExtra("name", name);
            MainActivity.this.startActivity(intent);    

        }
    });
于 2013-11-11T15:18:11.053 回答
0

要让 ArrayAdapter 做除了在可更新列表中显示 TextView 之外的任何事情,您必须对其进行子类化。下面是一个如何做到这一点的例子。

在 getView 方法中,您可以修改项目的视图并设置侦听器。

public class CustomAdapter extends ArrayAdapter<String>
{
    private LayoutInflater inflater;
    private int resourceId;
    private List<String> data;

    public CustomAdapter(Context context, int resourceId, List<String> data)
    {
        super(context, resourceId, data);
        inflater = LayoutInflater.from(context);
        this.resourceId = resourceId;
        this.data = data;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent)
    {
        if (view == null)
            view = inflater.inflate(resourceId, null);
        String data_item = (String) ((ListView) parent).getItemAtPosition(position);
        CheckBox checkBox = ((CheckBox) view.findViewById(R.id.check_box));
        // Do your thing
        return view;
    }
}
于 2013-11-11T14:49:54.140 回答