android实现ListView中动态添加RaidoButton单选
这里讲解的内容是:从数据库中取得数据,将这些数据的value值赋值给Radiobutton的text属性,将这些数据的key值赋值给radiobutton的key值。同时实现点击一整行,更换radiobutton选择。
XML代码:主要是添加一个ListView控件
public class TestActivity extends Activity { //初始化字符数组:arrayValue用于存放数据库中取得的key值,arrayText用于存放数据库中取得的Value值 String[] arrayValue; String[] arrayText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_item); //保证线程安全,防止多线程同时运行 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectAll() .build()); //初始化DBHelper final DBHelper dbHelper = new DBHelper(this); //查询业务类型语句 String sql = "select * from t_Test"; final Cursor cur = dbHelper.select(sql); // 防止数据库中无数据出错 if (cur != null && cur.getCount() > 0) {arrayText = new String[cur.getCount()];arrayValue = new String[cur.getCount()];// 移动到第一条记录cur.moveToFirst();int i = 0;int index = 0;// 遍历Cursor,把数据添加到数组中while (!cur.isAfterLast()) {index = cur.getColumnIndex("要查找的列名");arrayText[i] = cur.getString(index);index = cur.getColumnIndex("id");arrayValue[i] = cur.getString(index);i++;cur.moveToNext(); // 移动到下一条记录}} String[] contentString = arrayText; //创建listview适配器,存放取得的radiobutton ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_single_choice, contentString); ListView mylist = (ListView)findViewById(R.id.ListView01); mylist.setAdapter(arrayAdapter); //radiobutton监听事件 mylist.setOnItemClickListener(new OnItemClickListener() {public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {//将选择的radiobutton的Value值传入到实体类ApplicationData中appData.BusinessID =arrayValue[arg2];} }); //设置选择模式:单选模式 mylist.setChoiceMode(ListView.CHOICE_MODE_SINGLE); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_business_item, menu); return true; } }