无法从gridView获取对象

时间:2013-04-24 05:06:50

标签: android gridview baseadapter onitemclicklistener

我使用GridView创建了当前周的视图。我使用BaseAdapter生成GridView

这就是我给GridView

赋值的方法
        ArrayList<WeekCellItem> weekCellItems = getData(scheduleListdto);
    gridview1.setAdapter(new WeekAdapter(getApplicationContext(),weekCellItems));

当我点击CurrentItem上的每个单元格时,我需要GridView位置。

我为onItemClickListener

撰写了GridView
gridview1.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            Object o= gridview1.getItemAtPosition(arg2);
            Log.e("", "hhh");
        }
    });

我将对象'o'视为null。

(编辑)

我的weekAdapter

public class WeekAdapter extends BaseAdapter
{
Context mycontext;
ArrayList<String>weekHeads;
ArrayList<WeekCellItem> weekCellItems;
LayoutInflater inflater;
public WeekAdapter(Context c, ArrayList<WeekCellItem> items, ArrayList<String> obj)
{
    weekCellItems=items;
    weekHeads=obj;
    mycontext=c;
    inflater = LayoutInflater.from(c);
}
public int getCount() {
    // TODO Auto-generated method stub
    return weekCellItems.size();
}

public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return 0;
}

public View getView(int pos, View convertview, ViewGroup parent) {
    // TODO Auto-generated method stub
    viewHolder holder = new viewHolder();
    if(convertview==null)
    {
        convertview = inflater.inflate(R.layout.weekly_layout, null);
        holder.tv = (TextView) convertview.findViewById(R.id.textweeklylayout);
        convertview.setTag(holder);
    }
    else
        holder=(viewHolder)convertview.getTag();
    return convertview;
}
private static class viewHolder
{
    TextView tv;
}}

2 个答案:

答案 0 :(得分:2)

您需要实现适配器的getItem()方法。 gridview.getItemAtPosition()轮流调用适配器的getItem() - 方法。

您的WeekAdapter的getItem()返回null。那就是问题所在。它应该是:

public Object getItem(int arg0) {
    return weekCellItems.get(arg0); 
}

答案 1 :(得分:1)

添加以下代码。

public Object getItem(int arg0) {
    if (weekCellItems == null || weekCellItems.size() == 0)
        return null;

    return weekCellItems.get(arg0); 
}

为什么:您正在实施自定义适配器,因此您需要根据需要修改getItem()。