Bolic Bolic - 3 months ago 22
Android Question

Get child of RecyclerView

How can I access the children of a RecyclerView? I'm not looking for an onClickListener. I am trying to figure out how I can change the background of some TextViews in the RecyclerView. I have really no idea. Any advice would be appreciated.

Please note: the directly children are vertical

LinearLayout
s which contain
TextView
s.

public class MessdatenAdapter extends RecyclerView.Adapter<MessdatenAdapter.ViewHolder> {
private ArrayList<ArrayList<MessdatenColumn>> list = new ArrayList<ArrayList<MessdatenColumn>>();


public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public LinearLayout llVerticalContainer;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
llVerticalContainer = (LinearLayout) itemLayoutView.findViewById(R.id.layout_messdaten);
}
}

public MessdatenAdapter(ArrayList<ArrayList<MessdatenColumn>> list) {
this.list = list;
}

// Create new views (invoked by the layout manager)
@Override
public MessdatenAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {

View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_messdaten, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

ArrayList<MessdatenColumn> terminStringList = list.get(position);
LayoutInflater inflater = LayoutInflater.from(MainActivity.getMyAppCompatActivity());
holder.llVerticalContainer.removeAllViews();

for(int i = 0; i < terminStringList.size();i++){
TextView tv = (TextView) inflater.inflate(R.layout.item_messdaten_textview, null);

if(terminStringList.get(i).getValue().equals("NaN")){
tv.setText("-");
} else {
tv.setText(terminStringList.get(i).getValue());
}

if (i == 0) {
tv.setTypeface(null, Typeface.BOLD);
}
holder.llVerticalContainer.addView(tv);
}

}

@Override
public int getItemCount() {
return list.size();
}


}

Answer

Once you know the position of the child from the adapter,you can use LinearLayoutManager.getChildAt(index) to get the childview.

You can use this from the activity in itself.But be careful that you always query for a position which exists or else you will face an Incosistency Detected error.

Once you are done making the change,call RecyclerView.Adapter.notifyItemChanged (int position) .

Comments