ListView: how to access Item's elements programmatically from outside?

前端 未结 6 961
长情又很酷
长情又很酷 2021-01-22 02:17

I have the following situation.

I have a ListView, each item of the ListView is comprised of different widgets (TextViews, ImageViews, etc...) inflated form a Layout in

6条回答
  •  不思量自难忘°
    2021-01-22 02:27

    I assume you have a model object that you use to "draw" the list item , and for example the background color is determined based on a boolean or something.

    All you need to do, is change the value on which you base your decision which background color should that TextView have.

    Your getView() method should have code like that

    if (myModelObj.isBrown()) {
        myTextView.setBackgroundResource(R.drawable.brown_bg);
    else
        myTextView.setBackgroundResource(R.drawable.not_brown_bg);
    

    All you should do when ur event is triggered, is set the value of the brown boolean in your model and call notifyDataSetChanged() on your adapter

    EDIT

    If for some reason you don't wanna call nofitfyDataSetChanged(), althought it won't move the scroll position of your list and with the right recyclying it won't cause bad performance

    You can find the View object that represent the list item you want to edit-if it's visisble-, and simply change the background in it, without refreshing the list at all.

    int wantedPosition = 10; // Whatever position you're looking for
    int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount();
    int wantedChild = wantedPosition - firstPosition
    if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
        // Wanted item isn't displayed
        return;
    }
    View wantedView = listView.getChildAt(wantedChild);
    

    then use wantedView to edit your background

    This answer can be found here

提交回复
热议问题