10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ListViewで子要素(View)の取得。getChildAtがnullで困るなら…

Last updated at Posted at 2013-10-03

AndroidプログラミングでListViewを使用したとき、選択した項目のViewを取得したい時があると思います。
getChildAtでさっさと取得しようと思ってもスクロールに対応できずにnullが返ってくる。

ならカスタムアダプターでどうにかしてしまおう。

	Map<Integer, View> positionView = new HashMap<Integer, View>();
	/*もしくは
	SparseArray<View> positionView = new SparseArray<View>();*/
		
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
				
		View view = convertView;
		ViewHolder holder;
		SampleRow sr = (SampleRow)getItem(position);
				
		if(view == null){
			view = inflater.inflate(R.layout.sample_row, parent, false);
						
			holder = new ViewHolder();
			holder.nameView = (TextView)view.findViewById(R.id.sample_row_name);
						
			view.setTag(holder);
		}else{
			holder = (ViewHolder)view.getTag();
		}
				
		holder.nameView.setText(sr.getName());
				
		/*キーの重複不可を利用してgetViewで生成されるViewを格納*/
		positionView.put(position, view);
				
			return view;
		}
		
		public View getPositionView(int targetPosition){
			View targetView = positionView.get(targetPosition);
			return targetView;
		}

こうすればListViewを表示するActivity内onItemClickでpositionを取得して

getPositionView(position);

これで取得できます。

ただ、スクロールするたびカスタムアダプター側でコレクションにViewの格納をするので効率がいいかは…

10
10
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?