1. 程式人生 > >BaseAdapter 自定義介面卡設定網格佈局

BaseAdapter 自定義介面卡設定網格佈局

BaseAdapter 自定義介面卡:

public class imageAdpter extends BaseAdapter{

private Context c;//設定關聯上下文

//將圖片放到陣列中
private Integer img[]={
  R.drawable.addfolderr,
  R.drawable.app,
  R.drawable.app,
  R.drawable.audio,
  R.drawable.bbs,
  R.drawable.addfolderr,
  R.drawable.app,
  R.drawable.app,
  R.drawable.audio,
  R.drawable.bbs,
  R.drawable.addfolderr,
  R.drawable.app,
  R.drawable.app,
  R.drawable.audio,
  R.drawable.bbs,
  R.drawable.addfolderr,
  R.drawable.app,
  R.drawable.app,
  R.drawable.audio,
  R.drawable.bbs
};
public imageAdpter(Context context){
 c=context;
}
 @Override
 public int getCount() {
  // TODO Auto-generated method stub
  return img.length;
 }

 @Override
 public Object getItem(int position) {
  // TODO Auto-generated method stub
  return position;
 }

 @Override
 public long getItemId(int position) {
  // TODO Auto-generated method stub
  return position;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  ImageView image=new ImageView(c);//建立imageview控制元件放置圖片
  image.setImageResource(img[position]);
  image.setLayoutParams(new GridView.LayoutParams(120, 120));//設定圖片的大小
  image.setScaleType(ImageView.ScaleType.CENTER_CROP);//設定圖片比例
  return image;
 }

}

activity:

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GridView gridView=(GridView)findViewById(R.id.gridview);//獲取GridVIew控制元件
        gridView.setAdapter(new imageAdpter(this));//向控制元件中新增圖片
        gridView.setOnItemSelectedListener(new OnItemSelectedListener() {

   @Override
   public void onItemSelected(AdapterView<?> arg0, View arg1,
     int arg2, long arg3) {
    Toast.makeText(MainActivity.this, "ssss", 0).show();
    
   }

   @Override
   public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
    
   }
  });
    }