Reputation: 684
Here I defined a SiteAdapter and extends from ArrayAdapter:
public class SiteAdapter extends ArrayAdapter<Site> {
private int resourceId;
private List<Site> sites = null;
private Context context;
public SiteAdapter(Context context, int resource, List<Site> objects) {
super(context, resource, objects);
this.context = context;
this.resourceId = resource;
this.sites = objects;
}
@Override
public Site getItem(int position) {
return sites.get(position);
}
@Override
public int getCount() {
return sites.size();
}
//get the viewpage which inflate by site_layout.xml file
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Site site = getItem(position);
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(resourceId, null);
}
//this place we need to get the whole widget in site_layout.xml file
ImageView i1 = (ImageView) view.findViewById(R.id.thumbnail);
TextView address = (TextView) view.findViewById(R.id.address);
TextView t1 = (TextView) view.findViewById(R.id.name);
TextView t3 = (TextView) view.findViewById(R.id.distance);
i1.setImageResource(site.getImageId());
address.setText(site.getAddress());
String name = site.getName();
String result = parse(name);
//set name of the view
t1.setText(name);
t3.setText("<" + site.getDistance() + "m");
return view;
}
and in the MainActivity, I set the ListView using this site adapter, and I allocated an R.drawable.blank value to the only ImageView and now I need to change the ImageView, then get each row view through siteadapter getview method, the view returned but the question is why ImageView inside such view can't replace a new value(image), the result always turn out the previous R.drawable.blank ImageView:
here is MainActivity snippet:
View view = siteAdapter.getView(2, null, listView);
ImageView image1 = ((ImageView)view.findViewById(R.id.thumbnail));
image1.invalidate();
image1.setImageResource(R.drawable.amap_end);
siteAdapter.notifyDataSetChanged();
Upvotes: 2
Views: 2364
Reputation: 2278
The point is you do not have to call getView()
from your activity . It is only called by Adapter .
Now if you want to change your imageView
, you should change it from your sites list that is links to your adapter from activity , then call notifyDataSetChanged()
from adapter .
Activity :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// setUpViews
SiteAdapter adapter = new SiteAdapter(context,List<Site> sites);
listView.setAdapter(adapter);
// changing imageView
Site site = sites.get(position);
site.setImage(R.drawable.*);
// updating site into list with new image
sites.set(position,site);
// refresh the listView
adapter.notifyDataSetChanged();
However , consider to use RecycleView
instead of ListView
.
Upvotes: 1