2011-06-30 83 views
0

我想使用CustomAdapter填充ListView。我想給每個ListItem單獨的佈局。所以爲此,我重寫了我的CustomAdapter的getView()方法,如下所示。Android:使用CustomAdapter實現ListView

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,母體);

似乎有問題。調試器打開ListView.java類,然後該文件拋出一個InvocationTargetException,它打開ZygoteInit類,然後什麼也沒有發生。

我似乎不明白爲什麼myview不能用xml文件充氣。

我需要一些幫助。

回答

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; 
} 
相關問題