如何使用arrayadapter.getview方法

时间:2016-09-13 06:16:31

标签: android listview android-view

我在这里定义了 SiteAdapter ,并从 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;
}

在MainActivity中,我使用此站点适配器设置 ListView ,并将R.drawable.blank值分配给唯一的 ImageView ,现在我需要更改 ImageView ,然后通过siteadapter getview方法获取每个行视图,返回视图但问题是为什么 ImageView 这样的视图内部无法替换新值(图像) ,结果总是变成以前的R.drawable.blank ImageView:

这是MainActivity片段:

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();

1 个答案:

答案 0 :(得分:1)

重点是您不必从您的活动中致电getView()。它仅由适配器调用。

现在,如果您要更改imageView,则应从您的网站列表中更改它,该列表是从活动链接到适配器的链接,然后从适配器调用notifyDataSetChanged()

活动

 @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();

然而,考虑使用RecycleView代替ListView