0

I have a ListView that gets its layout for each item from "rowlayout".

I want to do something to one of the buttons in the rowlayout in my main activity, how do i get a reference to it findviewbyid doesn't work.

I guess i'm essentially not understanding a general concept of how to get a reference to a view in a custom layout- unless getting a view from a ListView is different. Can anyone help? thanks.

Vikasdeep Singh
  • 17,777
  • 9
  • 70
  • 93
Izak
  • 702
  • 6
  • 23

4 Answers4

1

ListView is a ViewGroup so you can just iterate over its children:

int n = getChildCount();
for (int i = 0; i < n; i++) {
    doSomethingToView(getChildAt(i));
}

However, you must be careful. ListView is pretty special and only has a subset of children that you might expect. It only holds (roughly) references to children that are currently visible and reuses them as they disappear.

What you might consider is changing underlying adapter instead and than notifying the ListView that its adapter changed, so it needs to redraw children. Or alternatively, you can make the child of ListView directly listen for events that are supposed to change it and then adjust itself.

gruszczy
  • 37,239
  • 27
  • 119
  • 167
1

If you are inflating a custom layout in the getView method of your adapter, you can get a view like this

LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View rowView = inflater.inflate(R.layout.your_custom_layout, parent, false);

TextView tv = (TextView) rowView.findViewById(R.id.your_tv_id);
jb15613
  • 357
  • 3
  • 12
  • and the above code can be called from my main activity if my adapter class is a seperate one? – Izak Apr 22 '15 at 02:56
  • No, this goes in the getView method of the adapter. Edit: sorry, just reread your question, didnt realise you wanted to access it in the activity. Please disreguard – jb15613 Apr 22 '15 at 03:02
0

You can use partial refresh principle if you implement ListView in the way of ViewHolder, just like this:

private void refreshPartially(int position){
    int firstVisiblePosition = listview.getFirstVisiblePosition();
    int lastVisiblePosition = listview.getLastVisiblePosition();
    if(position>=firstVisiblePosition && position<=lastVisiblePosition){
        View view = listview.getChildAt(position - firstVisiblePosition);
        if(view.getTag() instanceof ViewHolder){
            ViewHolder vh = (ViewHolder)view.getTag();
            //holder.play.setBackgroundResource(resId);//Do something here.
            ...
        }
    }
}
SilentKnight
  • 13,063
  • 18
  • 46
  • 76
0

Possibly you can use the answer from this android - listview get item view by position to get the child view at a position then call findViewById() on that child view.

Community
  • 1
  • 1
Tony Vu
  • 4,011
  • 2
  • 28
  • 36