当我运行以下代码时,复选框的名称将作为随机字符串出现(如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();
}
}
答案 0 :(得分: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中输入的文本。
希望这有帮助!