Android,ListView选项问题——getView刷新问题及单选框的实现本文地址:http://blog.csdn.net/you_and_me12/a
Android,ListView选项问题——getView刷新问题及单选框的实现
本文地址:http://blog.csdn.net/you_and_me12/article/details/8680421
2013-03-16
相关文章:ListView自定义后,在onItemClick中getChildAt返回null问题
导语:之前有讨论过ListView的getChildAt方法使用,还是很不了解,最近使用发现问题,经过几番折腾,终于搞定。
正文:
在重写的Adapter中,会有getView(),这个就是ListView布局的重点了。对于listView会有缓存即converView,其实有很多优化的方法就是资源重新利用了,加上if(converView == null)的判断语句,然后就不用每次重新创建一个item了,需要注意的是,如果converView不是null也需要对内容重写修改,否则list里面在翻页的时候会出现重复选项,原因是ListVIew会缓存可视界面的几个选项。所以getChildAt这个方法只能从可视界面中获取到值。
可以使用一种最简单的,就是不要判断converView是否为空,每次都重新创建。当需要对其他item做操作的时候就需要使用getChildAd的方法加上getFirstVisiblePosition()了,如果不在可视界面中,就不需要修改了,因为当你翻页到上头的时候界面是会重新刷新getView的,所以就不担心了。以下是我用ListView做的单选框部分代码,其中checkedIndex是记录选中的选项,仅供参考,勿喷!
/** * the adapter for this dialog's list view * @author K * */public class PersonsSelectAdapter extends SimpleAdapter {private Context mContext;private List<HashMap<String, Object>> mData;private int mResource;private SharedPreferences sp;/**To record the current radio button, which is checked*/private int checkedIndex = -1;public PersonsSelectAdapter(Context context, List<HashMap<String, Object>> data, int resource, String[] from, int[] to) {super(context, data, resource, from, to);mContext = context;mData = data;mResource = resource;sp = mContext.getSharedPreferences(mContext.getString(R.string.sp_name), mContext.MODE_PRIVATE);}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {//if(convertView == null)//can't should the 4th person{convertView = LayoutInflater.from(mContext).inflate(mResource, null);//radio buttonsRadioButton rb_selected = (RadioButton)convertView.findViewById(R.id.person_select_selected);rb_selected.setId(position);rb_selected.setChecked(sp.getBoolean((String)mData.get(position).get("preference_key"), false));if(rb_selected.isChecked())//goto this function two time with the same positioncheckedIndex = position;rb_selected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {if(isChecked){//set pre radio buttonif(checkedIndex != -1){int childId = checkedIndex - mListView.getFirstVisiblePosition();if(childId >= 0){View item = mListView.getChildAt(childId);if(item != null){RadioButton rb = (RadioButton)item.findViewById(checkedIndex);if(rb != null)rb.setChecked(false);}}sp.edit().putBoolean((String)mData.get(checkedIndex).get("preference_key"), false).commit();}//set cur radio buttoncheckedIndex = buttonView.getId();sp.edit().putBoolean((String)mData.get(checkedIndex).get("preference_key"), true).commit();}}});}return convertView;}}结尾: 1)坚持写写博客
2)继续学习安卓
3)我是IT程序猿
