Hello there,
I'm kind of new to Android, and I'm working on a simple image gallery. I have photo that is turned into Bitmap, then I cut it into 9 square(or equal) elements. Afterwards, I'm placing it to a GridView using my version of ImageAdapter. At last I want to make an effect that this squares randomly become transparent(gradient like from visible to transparent) and reavel another image beneath them(So the process can be repeated infinitely). I want to make it OnClick later to change photo, but right now I can't figure out how to make certain elements of GridView transparent. I tried using getChildAt(int index) or getItemAtPosition(int position) but all I get was NullPointerException. Can anyone help me with this? I tried to use many code samples across the web but none of it make it possible.
My main Activity:
public class MainActivity extends AppCompatActivity {
private int screenX;
private int screenY;
private ArrayList<Bitmap> chunkedImages;
private GridView gv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
RelativeLayout rl = (RelativeLayout)findViewById(R.id.RelativeLayout1);
rl.setBackgroundColor(Color.BLACK);
loadScreenXY();
ImageView view = new ImageView(this);
view.setImageResource(R.drawable.pizza);
this.chunkedImages = this.splitImage(view,9);
gv = (GridView) findViewById(R.id.GridView);
gv.setAdapter(new GridImageAdapter(this,this.chunkedImages));
gv.setNumColumns(3);
}
private void loadScreenXY() {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
this.screenX = size.x;
this.screenY = size.y;
}
private ArrayList<Bitmap> splitImage(ImageView image, int chunkNumbers) {
int rows,cols;
int chunkHeight;
int chunkWidth;
ArrayList<Bitmap> chunkedImages = new ArrayList<Bitmap>(chunkNumbers);
BitmapDrawable drawable = (BitmapDrawable) image.getDrawable();
Bitmap bitmap = drawable.getBitmap();
rows = cols = (int) Math.sqrt(chunkNumbers);
chunkHeight = bitmap.getHeight()/rows;
chunkWidth = bitmap.getWidth()/cols;
int yCoord = 0;
for(int x=0; x<rows; x++){
int xCoord = 0;
for(int y=0; y<cols; y++){
chunkedImages.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkWidth, chunkHeight));
xCoord += chunkWidth;
}
yCoord += chunkHeight;
}
return chunkedImages;
}
And my Adapter:
public class GridImageAdapter extends BaseAdapter{
private Context mContext;
private ArrayList<Bitmap> bm;
public GridImageAdapter(Context c, ArrayList<Bitmap> bm) {
mContext = c;
this.bm = bm;
}
public int getCount() {
return this.bm.size();
}
public Object getItem(int position) {
return null;
}
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(this.bm.get(position).getWidth(),this.bm.get(position).getHeight()));
imageView.setPadding(0,0,0,0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(this.bm.get(position));
return imageView;
}
}
Related
I want to achieve this screenshot like design with Horizontal scroll view.
I already done with the Horizontal scroll view with the help of Wheel view library
https://github.com/chemalarrea/Android-wheel
But I am not getting any idea about how to fill a color in this images without disturbing image square area using setBackground method for Imageview.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="15dp">
<kankan.wheel.widget.WheelView
android:id="#+id/slotwheel_look_color"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Adapter
private class SlotMachineAdapter_Look extends AbstractWheelAdapter {
// Image size
final int IMAGE_WIDTH = 100;
final int IMAGE_HEIGHT = 100;
private LayoutInflater mInflater;
private LinearLayout mLn_parant;
private ImageView mImg_condition;
// Layout inflater
private Context context;
// Slot machine symbols
private final int items[] = new int[]{
R.drawable.image_1,
R.drawable.image_2,
R.drawable.image_3,
R.drawable.image_4,
R.drawable.image_5,
R.drawable.image_6,
R.drawable.image_7,
R.drawable.image_8,
R.drawable.image_9
};
// Cached images
private List<SoftReference<Bitmap>> images;
/**
* Constructor
*/
public SlotMachineAdapter_Look(Context context) {
this.context = context;
mInflater = LayoutInflater.from(context);
images = new ArrayList<SoftReference<Bitmap>>(items.length);
for (int id : items) {
images.add(new SoftReference<Bitmap>(loadImage(id)));
}
}
/**
* Loads image from resources
*/
private Bitmap loadImage(int id) {
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id);
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
bitmap.recycle();
return scaled;
}
#Override
public int getItemsCount() {
return items.length;
}
// Layout params for image view
LayoutParams params = new LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
ImageView img;
if (cachedView != null) {
img = (ImageView) cachedView;
} else {
img = new ImageView(context);
}
img.setLayoutParams(params);
SoftReference<Bitmap> bitmapRef = images.get(index);
Bitmap bitmap = bitmapRef.get();
if (bitmap == null) {
bitmap = loadImage(items[index]);
images.set(index, new SoftReference<Bitmap>(bitmap));
}
BitmapDrawable ob = new BitmapDrawable(getResources(), bitmap);
img.setBackground(ob);
img.setImageBitmap(bitmap);
img.setColorFilter(Color.YELLOW);
return img;
// return view;
}
}
Please help me out for this issue.
Thanks in advance
Used the setColorFilter
Drawable myIcon = getResources().getDrawable( R.drawable.myicon);
ColorFilter filter = new LightingColorFilter( Color.BLUE, Color.BLUE );
myIcon.setColorFilter(filter);
Imageview.setImageDrawable(myIcon);
Or
Resources res = context.getResources();
final ImageView image = (ImageView) findViewById(R.id.image);
final int newColor = res.getColor(R.color.new_color);
image.setColorFilter(newColor, Mode.SRC_ATOP);
I am using List View with custom array adapter the adapter sets data from Sqlite. But when the list items reach over 10 (or list becomes scroll able) the Image View changes position automatically if i scrolls continue. here is my custom adapter's code.Thanks
public class CustomeAdapter extends ArrayAdapter<String>{
public Context context;
public ArrayList<String> titleArrayList, descArrayList, timeArrayList, imgArrayList, IdArrayList;
List data;
int layoutResID;
private Bitmap myBitmap;
public CustomeAdapter(Context context, int layoutResourceId, ArrayList<String> titleArrayList, ArrayList<String> descArrayList, ArrayList<String> timeArrayList, ArrayList<String> imgArrayList, ArrayList<String> IdArrayList) {
super(context, layoutResourceId, titleArrayList);
this.context = context;
this.titleArrayList = titleArrayList;
this.descArrayList = descArrayList;
this.timeArrayList = timeArrayList;
this.imgArrayList = imgArrayList;
this.IdArrayList = IdArrayList;
this.data = data;
this.layoutResID = layoutResourceId;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
final StockQuoteView sqView;
if (rowView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
rowView = inflater.inflate(layoutResID, parent, false);
sqView = new StockQuoteView();
sqView.tag = (TextView) rowView.findViewById(R.id.tv_fullnote);
sqView.desc = (TextView) rowView.findViewById(R.id.tv_title);
sqView.time = (TextView) rowView.findViewById(R.id.tv_time);
sqView.id = (TextView) rowView.findViewById(R.id.id);
sqView.img = (ImageView) rowView.findViewById(R.id.imageView3);
sqView.button1 = (ImageView) rowView.findViewById(R.id.swipe_button1);
sqView.button2 = (ImageView) rowView.findViewById(R.id.swipe_button2);
sqView.button3 = (ImageView) rowView.findViewById(R.id.swipe_button3);
sqView.button4 = (ImageView) rowView.findViewById(R.id.swipe_button4);
rowView.setTag(sqView);
} else {
sqView = (StockQuoteView) rowView.getTag();
}
try {
sqView.tag.setText(titleArrayList.get(position));
sqView.desc.setText(descArrayList.get(position));
sqView.time.setText(timeArrayList.get(position));
sqView.id.setText(IdArrayList.get(position));
sqView.id.setTag(IdArrayList.get(position).toString());
if (imgArrayList.get(position).contains("null")) {
sqView.img.setImageBitmap(null);
sqView.img.setTag("null");
} else {
myBitmap = BitmapFactory.decodeFile(imgArrayList.get(position));
//sqView.img.setImageBitmap((position & 1) == 1 ? myBitmap : myBitmap);
String TAG = "tag";
String id = String.valueOf(position);
sqView.img.setTag(imgArrayList.get(position).toString());
int width = myBitmap.getWidth();
int height = myBitmap.getHeight();
int newWidth = (height > width) ? width : height;
int newHeight = (height > width) ? height - (height - width) : height;
int crop = (width - height) / 2;
crop = (crop < 0) ? 0 : crop;
Bitmap cropImg = Bitmap.createBitmap(myBitmap, crop, 0, newWidth, newHeight);
sqView.img.setImageBitmap(cropImg);
}
} catch (Exception e) {
System.out.print(e.toString());
}
return rowView;
}
protected static class StockQuoteView {
protected TextView tag;
protected TextView desc;
protected TextView time;
protected ImageView img;
protected ImageView button1;
protected ImageView button2;
protected ImageView button3;
protected ImageView button4;
public TextView id;
}
}
`
put this linesqView.img.setVisibility(View.INVISIBLE) after sqView.img.setTag("null"); and Make Visible back the imageView in the else statment like else {sqView.img.setVisibility(View.VISIBLE)
myBitmap = BitmapFactory.decodeFile(imgArrayList.get(position));
//sqView.img.setImageBitmap((position & 1) == 1 ? myBitmap : myBitmap);
String TAG = "tag";
String id = String.valueOf(position);............}
this is tricked only.
//The Path where my images are saving
/storage/emulated/0/Pictures/CameraExample/JPEG_20150107_152640.jpeg
//This is one of the file path.
//I need to sort images like last taken photo as the first one to display //inside the grid view as of now images are displayed, recent photo at the //last.
Below is my code
public class ImageAdapter extends BaseAdapter{
private Context context;
private int imageWidth;
private Activity activity;
ArrayList<String> itemList = new ArrayList<String>();
Bitmap bitmap;
public ImageAdapter(Activity activity,ArrayList<String> itemList,int imageWidth) {
this.activity = activity;
this.itemList = itemList;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this.itemList.size();
}
void add(String path) {
itemList.add(path);
}
#Override
public Object getItem(int position) {
return this.itemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(activity);
}
else {
imageView = (ImageView) convertView;
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth ,imageWidth ));
bitmap = decodeFile(itemList.get(position), imageWidth, imageWidth);
imageView.setImageBitmap(bitmap);
imageView.setOnClickListener( new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements View.OnClickListener {
int position;
public OnImageClickListener(int position){
this.position = position;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, ImageDisplayActivity.class);
intent.putExtra("position", position);
Log.d("ImageAdapter","Intent.putExtra ");
activity.startActivity(intent);
}
}
public Bitmap decodeFile(String path, int reqWidth, int reqHeight) {
try {
File f = new File(path);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = reqWidth;
final int REQUIRED_HEIGHT = reqHeight;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH && o.outHeight / scale / 2 >= REQUIRED_HEIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
// And Finally when I scroll my grid view . Scrolling is not so smooth. Please help me in solving two problems.
// My GridView Activity Class
public class GridViewActivity extends Activity {
private ImageAdapter imageAdapter;
private HelperUtils utils;
private ArrayList<String> itemList = new ArrayList<String>();
private GridView gridView;
private int columnWidth;
private Activity activity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gridview);
gridView = (GridView) findViewById(R.id.gridView);
utils = new HelperUtils(this);
InitilizeGridLayout();
itemList = utils.getFilePaths();
imageAdapter = new ImageAdapter(this, itemList, columnWidth);
gridView.setAdapter(imageAdapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, HelperAppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((HelperAppConstant.NUM_OF_COLUMNS + 1) * padding)) / HelperAppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(HelperAppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding, (int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
}
Remove the Collections.sort(itemList); from your getView method.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
Log.d("ImageAdapter","Inside the if condition");
imageView = new ImageView(activity);
}
else {
imageView = (ImageView) convertView;
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth ,imageWidth ));
// bitmap = decodeFile(itemList.get(position), imageWidth, imageWidth);
bitmap = decodeFile(getItem(position), imageWidth, imageWidth);
imageView.setImageBitmap(bitmap);
return imageView;
}
Sort the list just before you populate your grid view in your onCreate method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gridview);
gridView = (GridView) findViewById(R.id.gridView);
utils = new HelperUtils(this);
InitilizeGridLayout();
itemList = utils.getFilePaths();
Collections.sort(itemList);
imageAdapter = new ImageAdapter(this, itemList, columnWidth);
gridView.setAdapter(imageAdapter);
}
You could follow the example in this link by creating a list of items that contains the image file path and the image bitmap. This way, you wouldn't have to decode the bitmap everytime getView is called. You could just decode it once before you populate the gridview.
Since the images are sorted in ascending order, you can replace you getItem method with the one below:
#Override
public Object getItem(int position) {
return this.itemList.get(itemList.size() - 1 - position);
}
I updated the getView method. You should use getItem(position) instead of itemList.get(position) to decode the bitmap.
For making your scroll smooth you have to display the images with Picasso library, I had the same issue !
I want to create 3x3 gridview programmatically for displaying images. And I want to set each item height and width by getting screen dimensions. Like:
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
Then each item width = screenWidth/3;
Please someone help me or some link for reference.
This is how you can create gridview programmatically,
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);
Add the above view to your layout. And here you can get the height and width of the display.
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay()
.getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;
And here is the adapter class :
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;
}
}
Then, It's upto you, If you are passing dynamic URL, change your adapter accordingly.
set your adapter to your gridview.
Let me know if you have any issues.
In your Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GridView gridView = new GridView(this);
gridView.setNumColumns(3);
setContentView(gridView);
gridView.setAdapter(new GridViewAdapter(this));
}
And Adapter:
private class GridViewAdapter extends BaseAdapter {
private Context context;
private final int length = 9;
public GridViewAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return 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);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels / 3;
int height = metrics.heightPixels / 3;
imageView.setLayoutParams(new GridView.LayoutParams(width, height));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(R.drawable.ic_launcher);
return imageView;
}
}
I found a tutorial on the Internet for an image slider but I don't know how to make it work on my phone. In the emulator it is giving me a message about setting nat directory path. I don't know how to do that. . .
Could anyone help me, please?
Code for Activities are:
Code for FullScreenViewActivity.java:
public class FullScreenViewActivity extends Activity{
private Utils utils;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
viewPager = (ViewPager) findViewById(R.id.pager);
utils = new Utils(getApplicationContext());
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,
utils.getFilePaths());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}
}
Code for GridViewActivity.java:
public class GridViewActivity extends Activity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
gridView = (GridView) findViewById(R.id.grid_view);
utils = new Utils(this);
// Initilizing Grid View
InitilizeGridLayout();
// loading all image paths from SD card
imagePaths = utils.getFilePaths();
// Gridview adapter
adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,
columnWidth);
// setting grid view adapter
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
}
Code for FullScreenImageAdapter.java:
public class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TouchImageView imgDisplay;
Button btnClose;
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
imgDisplay.setImageBitmap(bitmap);
// close button click event
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_activity.finish();
}
});
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this._filePaths.size();
}
#Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
} else {
imageView = (ImageView) convertView;
}
// get screen dimensions
Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
Intent i = new Intent(_activity, FullScreenViewActivity.class);
i.putExtra("position", _postion);
_activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
Code for GridViewImageAdapter.java:
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this._filePaths.size();
}
#Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
} else {
imageView = (ImageView) convertView;
}
// get screen dimensions
Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
Intent i = new Intent(_activity, FullScreenViewActivity.class);
i.putExtra("position", _postion);
_activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
util.java
public class Utils {
private Context _context;
// constructor
public Utils(Context context) {
this._context = context;
}
/*
* Reading file paths from SDCard
*/
public ArrayList<String> getFilePaths() {
ArrayList<String> filePaths = new ArrayList<String>();
File directory = new File(
android.os.Environment.getExternalStorageDirectory()
+ File.separator + AppConstant.PHOTO_ALBUM);
// check for directory
if (directory.isDirectory()) {
// getting list of file paths
File[] listFiles = directory.listFiles();
// Check for count
if (listFiles.length > 0) {
// loop through all files
for (int i = 0; i < listFiles.length; i++) {
// get file path
String filePath = listFiles[i].getAbsolutePath();
// check for supported file extension
if (IsSupportedFile(filePath)) {
// Add image path to array list
filePaths.add(filePath);
}
}
} else {
// image directory is empty
Toast.makeText(
_context,
AppConstant.PHOTO_ALBUM
+ " is empty. Please load some images in it !",
Toast.LENGTH_LONG).show();
}
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(_context);
alert.setTitle("Error!");
alert.setMessage(AppConstant.PHOTO_ALBUM
+ " directory path is not valid! Please set the image directory name AppConstant.java class");
alert.setPositiveButton("OK", null);
alert.show();
}
return filePaths;
}
/*
* Check supported file extensions
*
* #returns boolean
*/
private boolean IsSupportedFile(String filePath) {
String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
filePath.length());
if (AppConstant.FILE_EXTN
.contains(ext.toLowerCase(Locale.getDefault())))
return true;
else
return false;
}
/*
* getting screen width
*/
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) _context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
}
AppConstant.java
public class AppConstant {
// Number of columns of Grid View
public static final int NUM_OF_COLUMNS = 3;
// Gridview image padding
public static final int GRID_PADDING = 8; // in dp
// SD card image directory
public static final String PHOTO_ALBUM = "NAT";
// supported file formats
public static final List<String> FILE_EXTN = Arrays.asList("jpg", "jpeg",
"png");
}
The only problem is setting the nat directory path so that it works on my phone.
I had the same problem (same tutorial :D), the problem is that you need a place to store all the wallpapers, so just change
// SD card image directory
public static final String PHOTO_ALBUM = "NAT";
to
// SD card image directory
public static final String PHOTO_ALBUM = "Camera";
for example to show the cameras pics.
public static final String PHOTO_ALBUM =Environment.getExternalStorageDirectory().getPath()+ "/DCIM/"+"/100ANDRO/";
"/DCIM/100ANDRO/" is a path where my Pictures are stored.
just change NAT by DCIM/Camera here your internal phone memory pics. i tried this and its work but some other problem occurs, when i click any pic then application is force stop if you resolve this problem then let m know. thank you