0

当我运行以下代码时,复选框的名称以随机字符串的形式出现(例如android.widget.CheckBox@43e641b0。)我也无法单击那些添加的复选框。

这是我的java代码:

package com.srk.android.rough1;
import java.util.ArrayList;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.app.ListActivity;


public class Rough1Activity extends ListActivity {
   ArrayList<CheckBox> listItems=new ArrayList<CheckBox>();
   ArrayAdapter<CheckBox> adapter;
   private EditText taskNameEditText;

   @Override
   public void onCreate(Bundle icicle) {
       super.onCreate(icicle);
       setContentView(R.layout.main);
       adapter=new ArrayAdapter<CheckBox>(this, android.R.layout.simple_list_item_multiple_choice, listItems);
       setListAdapter(adapter);
   }

   public void addItems(View v) {
       taskNameEditText=(EditText)findViewById(R.id.TaskName);
       String taskName=taskNameEditText.getText().toString();
       CheckBox cb=new CheckBox(this);
       cb.setText(taskName);
       listItems.add(cb);
       adapter.notifyDataSetChanged();
   }
}
4

1 回答 1

0

您正在尝试显示 CheckBoxes,就像添加整数或字符串数​​组一样...我建议采用不同的方法:

public class Rough1Activity extends ListActivity {
    private ArrayList<String> listItems = new ArrayList<String>();
    private ArrayAdapter<String> adapter;
    private EditText taskNameEditText;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        // I like this layout, but it's your choice
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, listItems);
        //adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, listItems);
        setListAdapter(adapter);

        // I guessed that you want a multiple choice list from your first layout choice. This is optional, you can remove it.
        ListView listView = getListView();
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        // Here you only need to initialize taskNameEditText once 
        taskNameEditText = (EditText) findViewById(R.id.TaskName);
    }

    public void addItems(View v) {
        // Add the current string in the EditText to the ListView
        adapter.add(taskNameEditText.getText().toString());
    }
}

您想要一个字符串列表并使用复选框显示字符串。我将您的 ArrayList 和 ArrayAdapter 更改为 String 子类型以反映这一点,并且布局android.R.layout.simple_list_item_checked本身添加了 Checkbox 功能。现在用户将看到他们在 ListView 中输入的带有可检查行的文本。

希望这可以帮助!

于 2012-08-12T18:13:51.513 回答