這裏我創建自定義列表視圖與複選框/ RadioButton。我得到了這個,但我需要單一的選擇。自定義ListView與CheckBox單選
我嘗試使用這個lstvw.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
但它不是爲我工作。有沒有其他解決方案,請讓我知道。
main.java
private ImageAdapter adapter;
private static String month[] = {"January","February","March","April","May",
"June","July","August","September",
"October","November","December"};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lstvw = (ListView) findViewById(R.id.listView);
adapter = new ImageAdapter(this, month);
lstvw.setAdapter(adapter);
lstvw.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lstvw.setOnItemClickListener(this);
}
我不知道該如何添加代碼的複選框插入適配器class.please檢查適配器類,如下。
ImageAdapter.class
public class ImageAdapter extends BaseAdapter{
public String title[];
public String description[];
public Activity context;
public LayoutInflater inflater;
public ImageAdapter(Activity context,String[] title) {
super();
this.context = context;
this.title = title;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
TextView txtViewTitle;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView==null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.listitem, null);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.lstvw_textView);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.txtViewTitle.setText(title[position]);
return convertView;
}
}
編輯:
Listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/lstvw_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/itemCheckBox"
android:padding="8dp"
android:text="hello world" />
<CheckBox
android:id="@+id/itemCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:gravity="right" />
使用RadioButton進行單選而不是ListView。 – 2012-08-17 07:05:28
是否想通過單選按鈕或多選複選框在整個列表中選擇一個項目? – swiftBoy 2012-08-17 07:18:21
@RDC是的,我只想單個項目選擇 – 2012-08-17 08:10:04