GridView的getChildAt(postion)獲取不到指定位置的item的解決方法(動態設定指定item為選中狀態)
阿新 • • 發佈:2019-01-28
問題描述:
有時候需要在GridView中設定某一個item為預設選中狀態,對應做一些處理,
最方便的自然是用getChildAt(postion)方法直接獲取item的view進行設定就行了
但是很多時候這個方法返回的view為null,用getAdapter.getview(postion,null,null)也可以獲取指定位置item的view,但是並不能進行修改,是沒有效果的,類似要實現下圖這種進入就讓第二個item為選中狀態,顯示下方三角箭頭,圖片加上外框背景,改變對應字型顏色等
這種用上述方法就不好使了,但是有一個思路很另類的方法可以完美實現,不用處理和擔心item的view為空的問題,那就是重新複製一個GridView的adpter類,在需要的時候重新setadapter,在adapter中進行處理,如下圖所示:
就是在adapter的重寫的getview方法中進行設定,複製的adapter在載入的時候除了context,資料來源list集合,再傳入一個需要制定預設選中item的位置postion
程式碼表示如下:
public AllGVAdapterbylevel(List<Map<String, Object>> list, Context context,int location) {
this.list = list;
this.context = context;
this.pos=location;
inflater= LayoutInflater.from(context);
}
、、、、、、、
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
//載入item佈局 將xml佈局載入到記憶體中,形成一個view
if(convertView==null){ //被複用後的convertview類依然包含tag
holder=new ViewHolder();
convertView=inflater.inflate(R.layout.tequan_gridview_item,null);
holder.iv_huanyuan_zuo= (ImageView) convertView.findViewById(R.id.iv_huanyuan_zuo);
holder.zhishiyou= (ImageView) convertView.findViewById(R.id.zhishiyou);
holder.zhishiup= (ImageView) convertView.findViewById(R.id.zhishiup);
holder.iv_huanyuan_bg= (ImageView) convertView.findViewById(R.id.iv_huanyuan_bg);
holder.needjifent= (TextView) convertView.findViewById(R.id.needjifent);
if (position==0){
holder.zhishiyou.setVisibility(View.INVISIBLE);
// holder.zhishiup.setVisibility(View.VISIBLE);
// holder.needjifent.setTextColor(Color.parseColor("#da408a"));
// holder.iv_huanyuan_bg.setVisibility(View.VISIBLE);
}
if (position==pos){
// holder.zhishiyou.setVisibility(View.INVISIBLE);
holder.zhishiup.setVisibility(View.VISIBLE);
holder.needjifent.setTextColor(Color.parseColor("#da408a"));
holder.iv_huanyuan_bg.setVisibility(View.VISIBLE);
}
convertView.setTag(holder);
}else {//convertview不為空,不為空則說明convertview包含tag
holder= (ViewHolder) convertView.getTag();
}
Map<String,Object> map= (Map<String, Object>) getItem(position);
holder.iv_huanyuan_zuo.setImageResource((Integer) map.get("img"));
holder.needjifent.setText((String) map.get("txt"));
itemView=convertView;
return convertView;
}
載入adapter時候加入位置引數:
allGVAdapterbylevel=new AllGVAdapterbylevel(list_alltequanxian,this,levelTQ-1);
這種方法適用於一個頁面有兩個入口,一個就是進入頁面預設選中第一個item為選中狀態,第二個入口為根據使用者資訊動態設定item的選中狀態,就可以通過這種用兩個adapter的方法進行設定,繞開getChildAt方法