2014-03-13 123 views
5

我想以編程方式創建3x3 gridview來顯示圖像。我想通過獲取屏幕尺寸來設置每個項目的高度和寬度。像:如何在android中以編程方式創建GridView圖像庫?

DisplayMetrics metrics = context.getResources().getDisplayMetrics(); 
int width = metrics.widthPixels; 
int height = metrics.heightPixels; 

,每個項目width = screenWidth/3;

請幫助我的人或一些鏈接以供參考。

回答

10

這是如何通過編程創建的GridView,

GridView grid = new GridView(this); 
    grid.setId(ViewIdentification.getId()); 
    grid.setLayoutParams(new GridView.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); 
    grid.setBackgroundColor(Color.WHITE); 
    grid.setNumColumns(3); 
    grid.setColumnWidth(GridView.AUTO_FIT); 
    grid.setVerticalSpacing(5); 
    grid.setHorizontalSpacing(5); 
    grid.setStretchMode(GridView.STRETCH_COLUMN_WIDTH); 

添加上述觀點來佈局。在這裏你可以得到顯示器的高度和寬度。

DisplayMetrics displaymetrics = new DisplayMetrics(); 
getWindowManager().getDefaultDisplay() 
      .getMetrics(displaymetrics); 
int width = displaymetrics.widthPixels; 
int height = displaymetrics.heightPixels; 

這裏是適配器類:

public class ImageAdapter extends BaseAdapter { 

    private Context mContext; 
    private Bitmap[]mis_fotos; 

    public ImageAdapter(Context c) { 
     mContext = c; } 

    public int getCount() { 
     return mis_fotos.length; 
     } 

    public Object getItem(int position) { 
     return position; } 

    public long getItemId(int position) { 
     return 0; } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     ImageView imageView; 
     if (convertView == null) { 
      imageView = new ImageView(mContext); 
      imageView.setLayoutParams(new GridView.LayoutParams(width/3, height/3)); 
      imageView.setScaleType(ImageView.setScaleType(ScaleType.FIT_XY)); 
      imageView.setPadding(0, 0, 0, 0); 
     } else { 
      imageView = (ImageView) convertView; 
     } 
     imageView.setImageBitmap(mis_fotos[position]); 
     return imageView; 
    } 
} 

然後,它高達你,如果你是通過動態的URL,相應地改變你的適配器。 將你的適配器設置爲你的gridview。 如果您有任何問題,請告知我。

+0

其中我必須寫上述2個部分? –

+0

在'OnCreate'中創建一個gridview並獲取寬度和高度。之後創建適配器類 –

+0

您可以請發佈完整的代碼? –

2

在你的活動:

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
GridView gridView = new GridView(this); 
gridView.setNumColumns(3); 
setContentView(gridView); 
gridView.setAdapter(new GridViewAdapter(this)); 
} 

和轉接:

相關問題