How to use CustomAdapter with ListView from XML Async Task

Deadly 提交于 2019-12-08 20:07:30

Create a custom adapter as following:

public class ArrayAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
private List<String> listString;

public ArrayAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data = d;
    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//your getView method here
}

GetView Method

public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.custom, null);

        TextView tv1 = (TextView) vi.findViewById(R.id.tvone);
        TextView tv2 = (TextView) vi.findViewById(R.id.tvtwo);
        HashMap<String, String> map = new HashMap<String, String>();
        map = data.get(position);
        tv1.setText(map.get("KEY1"));
        tv2.setText(map.get("KEY2"));
        return vi;
    }

Make array list as:

ArrayList<HashMap<String, String>> yourList;

And fill yourList as

HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("KEY1", value1);
map.put("KEY2", value2);
yourList.add(map);

And while making object of the custom adapter

CustomAdapter adapter = new CustomAdapter(YourActivity.this, yourList);
list.setAdapter(adapter);

For list you can do

list = (ListView) getView().findViewById(android.R.id.list);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!