2013-08-20 34 views
0

我按照the tutorial about the GridView。我試圖通過適配器將ImageView與佈局xml文件中的GridView綁定。我從mainActivity捕獲了ImageView,並通過ImageAdapter的構造函數輸入ImageView或使ImageView爲靜態,從而嘗試了兩種方法。他們都返回運行時異常。將ImageView與GridView綁定

//capturing imageView in the mainActivity 

     public static ImageView IMAGE_VIEW; 
      IMAGE_VIEW=(ImageView) findViewById(R.id.imageView1); 



public class ImageAdapter extends BaseAdapter{ 
    private Context mContext; 

public ImageAdapter(Context c) { 
     mContext = c; 
    } 
public int getCount() { 
     // It should return 16 ImageViews 
     return 16; 
    } 
. 
. 
. 

    public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView imageView; 
      if (convertView == null) { // if it's not recycled, initialize some attributes 
       imageView = new ImageView(mContext); 
       imageView.setLayoutParams(new GridView.LayoutParams(150, 150)); 
       imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
       imageView.setPadding(20, 20, 4, 4); 
      } else { 
       imageView = (ImageView) convertView; 
      } 


       imageView=MainActivity.IMAGE_VIEW; //I suppose here is the problem 

    // the code underneath works fine for an Image File not for the ImageView  
    // imageView.setImageResource(R.drawable.crazy); 


      return imageView; 
     } 
} 

這是什麼錯誤?解決方案是什麼?

回答

-1

嘗試做這樣的。 在你的主XML文件:

<GridView 
    android:id="@+id/gridView1" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
</GridView> 

在XML文件中描述的網格項:

<TextView 
    android:id="@+id/item_title" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@drawable/ic_launcher"> 
</TextView> 

適配器:

// references to our images 
public int[] mThumbIds = { 
     R.drawable.icon_1, 
     R.drawable.icon_2, 
     R.drawable.icon_3, 
     R.drawable.icon_4, 
     R.drawable.icon_5, 
     R.drawable.icon_6 
}; 

的方法getView:

TextView item = (TextView) view.findViewById(R.id.item_title); 
    item.setBackgroundResource(mThumbIds[position]); 

活動:

// set grid menu 
GridView gridview = (GridView) view.findViewById(R.id.gridView1); 
YourAdapter adapter = new YourAdapter(); //put here your arguments 
gridview.setAdapter(leftMenuAdapter);