MainActivity.java
package kanta.gridview_image; import android.app.Activity; import android.os.Bundle; import android.widget.GridView; public class MainActivity extends Activity { GridView gridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridView=(GridView)findViewById(R.id.gridView); ImageAdapter adapter=new ImageAdapter(this); gridView.setAdapter(adapter); } }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="kanta.gridview_image.MainActivity"> <GridView android:id="@+id/gridView" android:layout_width="match_parent" android:layout_height="match_parent" android:columnWidth="90dp" android:gravity="center" android:horizontalSpacing="10dp" android:numColumns="auto_fit" android:stretchMode="columnWidth" android:verticalSpacing="10dp" /> </LinearLayout>
ImageAdapter.java
package kanta.gridview_image; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; /** * Created by kanta on 30-Apr-16. */ public class ImageAdapter extends BaseAdapter { int[] mThumbIds = { R.drawable.china, R.drawable.india, R.drawable.japan, R.drawable.united_kingdom, R.drawable.united_states, R.drawable.china, R.drawable.india, R.drawable.japan, R.drawable.united_kingdom, R.drawable.united_states, R.drawable.china, R.drawable.india, R.drawable.japan, R.drawable.united_kingdom, R.drawable.united_states }; Context context; public ImageAdapter(MainActivity mainActivity) { this.context = mainActivity; } @Override public int getCount() { return mThumbIds.length; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(context); imageView.setLayoutParams(new GridView.LayoutParams(300, 300)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } }
No comments:
Post a Comment