When decided to learn about GridView, thought will look at the Android Sample itself. Found the sample at the link given in Android website very useful.
The code was pretty simple. First had to add the grid view to the layout xml file
The code was like the below
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
Reference:
http://developer.android.com/guide/topics/ui/layout/gridview.html
The code was pretty simple. First had to add the grid view to the layout xml file
The code was like the below
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
Now, in the main activity on create, below code needs to be added
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Toast.makeText(GridViewSampleActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
Just create the subclass of BaseAdapter and override the getView function
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(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
I gave the layout param as 200 x 200 gave a good looking grid view, however, on orientation chagne, all the grid items were overlapping without any gap. Need to check this.
Reference:
http://developer.android.com/guide/topics/ui/layout/gridview.html
No comments:
Post a Comment