本文地址: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程式猿