2012-08-12 116 views
0

當我運行下面的代碼時,複選框的名稱會隨機出現(如[email protected])。我也無法單擊添加的複選框。將複選框添加到Android的列表視圖中

這是我的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

您正在試圖顯示一個複選框,你會添加整數或字符串數​​組...我提出一個不同的方法:

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本身添加了複選框功能。現在,用戶將看到他們在具有可檢查行的ListView中輸入的文本。

希望這會有所幫助!

相關問題