Android:使用自定义适配器实现ListView

时间:2011-06-30 10:01:51

标签: android android-listview

我正在尝试使用CustomAdapter填充ListView。我想为每个ListItem提供单独的布局。因此,为此我覆盖了CustomAdapter的getView()方法,如下所示。

public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    // This is where our ListView is constantly going to ask the Adapter for all the Views that it needs
    View myview;
    ImageView pic;


    TextView text;

    if(convertView==null)
    {    

        **myview=View.inflate(mycontext,R.layout.customrow, parent);**
        pic=(ImageView)myview.findViewById(R.id.pic);
        pic.setLayoutParams(new ListView.LayoutParams(100,100));
        //text=(TextView)myview.findViewById(R.id.text);
        //text.setTextSize(14);


    }
    else
        myview=convertView;

    if(cache[position]==null)
    {
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inSampleSize=10;
        Bitmap thumb=BitmapFactory.decodeResource(mycontext.getResources(), Images[position], options);
        cache[position]=thumb;

    }
    pic=(ImageView)myview.findViewById(R.id.pic);
    //text=(TextView)myview.findViewById(R.id.text);
    pic.setImageBitmap(cache[position]);
    //text.setText(titles[position]);



    return myview;
}

但是,当我尝试调试行 myview = View.inflate(mycontext,R.layout.customrow,parent);

似乎有问题。调试器打开ListView.java类,然后该文件抛出一个InvocationTargetException,它打开ZygoteInit类,然后没有任何反应。

我似乎不明白为什么myview无法通过xml文件充气。

我需要一些帮助。

1 个答案:

答案 0 :(得分:0)

请尝试使用LayoutInflator

public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    // This is where our ListView is constantly going to ask the Adapter for all the Views that it needs
    View myview;
    ImageView pic;


    TextView text;

    if(convertView==null)
    {    
        LayoutInflater li = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        myview=li.inflate( R.layout.customrow, null );
        pic=(ImageView)myview.findViewById(R.id.pic);
        pic.setLayoutParams(new ListView.LayoutParams(100,100));
        //text=(TextView)myview.findViewById(R.id.text);
        //text.setTextSize(14);


    }
    else
        myview=convertView;

    if(cache[position]==null)
    {
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inSampleSize=10;
        Bitmap thumb=BitmapFactory.decodeResource(mycontext.getResources(), Images[position], options);
        cache[position]=thumb;

    }
    pic=(ImageView)myview.findViewById(R.id.pic);
    //text=(TextView)myview.findViewById(R.id.text);
    pic.setImageBitmap(cache[position]);
    //text.setText(titles[position]);



    return myview;
}