2013年9月5日星期四

gridview Adapter how to write

Rewritten BaseAdapter

@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView imageView;
if(arg1 == null){
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(45,45));
imageView.setAdjustViewBounds(false);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}else{
imageView = (ImageView) arg1;
}
Resources res=getResources();  
int i=res.getIdentifier(arr[arg0],"drawable",getPackageName());  
imageView.setImageResource(R.drawable.default_pic);
return imageView;
}


more correct
now want to use to complete the layout file , I put it amended as follows

public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
View v ;
if(arg1 == null){
v = (View) findViewById(R.layout.items_img);
ImageView iv1 = (ImageView) v.findViewById(R.id.ItemImage1);
ImageView iv2 = (ImageView) v.findViewById(R.id.ItemImage2);
iv1.setImageResource(R.drawable.default_pic);
iv2.setImageResource(R.drawable.checkbox1);
}else{
v = (ImageView) arg1;
}
return v;
}

items_img.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView
    android:id="@+id/ItemImage1"
    android:layout_width="100dip"
    android:layout_height="100dip"
    android:layout_centerHorizontal="true"/>
<ImageView
    android:id="@+id/ItemImage2"
    android:layout_width="40dip"
    android:layout_height="40dip"
    android:src="@drawable/checkbox1"
    />
</RelativeLayout>

Run error, null pointer this line that I can not ah !
ImageView iv1 = (ImageView) v.findViewById (R.id.ItemImage1);
------ Solution ------------- -------------------------------
v = (View) findViewById (R. layout.items_img); wrong here , v not find out, is loaded out LayoutInflator
v = LayoutInflater.from (mContext). inflate (R.layout.home_grid_item, null);
------ Solution ----------- ---------------------------------
manually load xml file first and then find, just find a demo you can see the
------ Solution -------------------------------- ------------
1 Floor positive solution inflate
------ Solution --------------------- -----------------------
1 Floor positive solution, or direct access to system services
LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService (LAYOUT_INFLATER_SERVICE);
ViewGroup menuView = (ViewGroup) mLayoutInflater.inflate (
R.layout.gridview_pop, null, true);
menuGrid = (GridView) menuView.findViewById (R.id.gridview);

just like this
------ For reference only ----------------------------- ----------
manually load xml file first and then find, just look for a demo , you can see the

没有评论:

发表评论