Encountering lag when updating a CardView item in a RecycleView - java

i'm having an issue working with CardViews . I`ve created a CardView containing 1 TextView and 2 ImageViews , which gets displayed in an RecycleView . When i try to update the contents of one of the CardViews (created 5 cards for testing) the interface starts to lag when scrolling over the updated card, but goes back to normal when i pass the item. It only happens when ImageViews are present , when substituting the ImageViews for say, TextViews with some random text in them, it works normally.
Now, here's my code , after that i'll add some more information that could be causing it.
First , the Adapter class, which also contains the items class and List :
public class MovieDetailsAdapter extends RecyclerView.Adapter<MovieDetailsAdapter.MovieViewHolder> {
public List<MovieDetails> movieList;
private static final String TAG = "MyAdapter";
public MovieDetailsAdapter() {
movieList = new ArrayList< MovieDetails>();
}
public void setItemCount(int count ,String title, Bitmap poster,Bitmap fanart ) {
movieList.clear();
movieList.addAll(generateDummyData(count, title, poster , fanart));
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return movieList.size();
}
public void addItem(int position,String title, Bitmap poster, Bitmap fanart) {
if (position > movieList.size()) return;
movieList.add(position, generateDummyItem(title, poster, fanart));
// notifyDataSetChanged();
notifyItemInserted(position);
}
public void updateItem(int position, String title, Bitmap poster, Bitmap fanart) {
if (position > movieList.size()) return;
movieList.add(position, generateDummyItem(title, poster, fanart));
notifyItemChanged(position);
// notifyDataSetChanged();
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout_movies, viewGroup, false);
Log.d(TAG, "create header view holder");
return new MovieViewHolder(itemView);
}
#Override
public void onBindViewHolder(MovieViewHolder movieViewHolder, int i) {
Log.d(TAG, "bind header view holder");
MovieDetails mdet = movieList.get(i);
movieViewHolder.vTitle.setText(mdet.Title);
movieViewHolder.vPoster.setImageBitmap(mdet.imageViewPoster);
movieViewHolder.vFanart.setImageBitmap(mdet.imageViewFanart);
Log.d(TAG, "position: " + i + " holder: " + movieViewHolder + " text: " + movieViewHolder.vTitle);
}
public static class MovieViewHolder extends RecyclerView.ViewHolder {
protected TextView vTitle;
protected ImageView vPoster;
protected ImageView vFanart;
public MovieViewHolder(View v)
{
super(v);
vTitle = (TextView) v.findViewById(R.id.title);
vPoster = (ImageView) v.findViewById(R.id.imageViewPoster);
vFanart = (ImageView) v.findViewById(R.id.imageViewFanart);
}
}
public static class MovieDetails {
protected String title;
protected Bitmap imageViewPoster;
protected Bitmap imageViewFanart;
public MovieDetails(String title, Bitmap imageViewPoster,Bitmap imageViewFanart )
{
this.title = title;
this.imageViewPoster = imageViewPoster;
this.imageViewFanart = imageViewFanart;
}
}
public static MovieDetails generateDummyItem(String title, Bitmap poster, Bitmap fanart) {
MovieDetails mov = new MovieDetails(title, poster, fanart);
return mov;
}
public static List< MovieDetailsAdapter.MovieDetails> generateDummyData(int count, String title , Bitmap imageViewPoster, Bitmap imageviewFanart) {
ArrayList<MovieDetailsAdapter.MovieDetails> items = new ArrayList<MovieDetailsAdapter.MovieDetails>();
for (int i=0; i < count; i++) {
items.add(new MovieDetailsAdapter.MovieDetails(title, imageViewPoster, imageviewFanart));
}
return items;
}
}
Now, here is my main class , the activity class
public class MoviesListActivity extends AppCompatActivity {
public MovieDetailsAdapter ca = new MovieDetailsAdapter();
public RecyclerView recList;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies_list);
RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
button = (Button) findViewById(R.id.button);
MyOnClickListener Listener = new MyOnClickListener();
button.setOnClickListener(Listener);
recList.setItemAnimator(null);
Bitmap bittest1 = decodeSampledBitmapFromResource(getResources(), R.drawable.poster_example, 640, 955);
Bitmap bittest2 = decodeSampledBitmapFromResource(getResources(), R.drawable.fanart_example, 800, 450);
ca.setItemCount(5, "TestingTitle", bittest1, bittest2);
recList.setAdapter(ca);
}
public class MyOnClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
Bitmap bittest12 = decodeSampledBitmapFromResource(getResources(), R.drawable.poster2, 640, 955);
Bitmap bittest22 = decodeSampledBitmapFromResource(getResources(), R.drawable.fanart2, 800, 450);
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
ca.updateItem(1, "test", bittest12, bittest22);
// ca.addItem(1,"test",bittest12,bittest22);
break;
default:
break;
}
}
}
//------methods used for resizing the images down to smaller ones before loading into memory---//
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
And finally, not that i probably matters, my CardView XML.
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#color/bkg_card"
android:text="Movie Title"
android:gravity="center_vertical"
android:textColor="#android:color/white"
android:textSize="14dp"/>
<ImageView
android:elevation="5dp"
android:scaleType="fitCenter"
android:layout_width="100dp"
android:layout_height="150dp"
android:id="#+id/imageViewPoster"
android:text="Poster"
android:gravity="center_vertical"
android:layout_below="#id/title"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"/>
<ImageView
android:id="#+id/imageViewFanart"
android:scaleType="fitCenter"
android:layout_alignBottom="#+id/imageViewPoster"
android:layout_toEndOf="#+id/imageViewPoster"
android:layout_width= "235dp"
android:layout_height="122dp"
android:layout_marginRight="5dp"/>
</RelativeLayout>
Now , somebody in another discussion showed me this as a possible cause : Why RecyclerView.notifyItemChanged() will create a new ViewHolder and use both the old ViewHolder and new one?
So i added the Log items inside the onBind and onCreate methods of the Adapter to see if that could be causing it, and indeed, it`s not just creatind one additional ViewHolders, but 3 of them, and each time i scroll over the newly updated card, it seems to be re-binding, the onBind method seems to be called each time.
Setting the animation to 'null' as per the solution in the thread doesn't seem to have any effect in my case, so maybe that`s not what is causing it.
Any ideas ?

Well, i solved it. It seems to happen only when i'm loading the images via the XML method, if i load them with a 3rd party library like Picasso, the lag seems to dissapear. Something like :
Picasso.with(context).load(MovieDetails.getPoster())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(movieViewHolder.imageViewPoster);
inside the onBindViewHolder
and instead of passing around bitmaps, just pass a String for the URL or location of the image. And pass the Context to the Adapter class.

Related

How to make an image shower larger from thumbnail in android?

I Have successfully started reading images back into my android app into a gridview, I need help now. When a user clicks on an image I want it to appear larger from the thumbnail. Any help is much appreciated.
My code for the images to get read :
[code]
public class View_Pictures extends AppCompatActivity {
public class ImageAdapter extends BaseAdapter {
private Context mContext;
ArrayList<String> itemList = new ArrayList<String>();
public ImageAdapter(Context c) {
mContext = c;
}
void add(String path){
itemList.add(path);
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
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(220, 220));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);
imageView.setImageBitmap(bm);
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
}
ImageAdapter myImageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view__pictures);
GridView gridview = (GridView) findViewById(R.id.gridview);
myImageAdapter = new ImageAdapter(this);
gridview.setAdapter(myImageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Venns Road Accident";
Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files){
myImageAdapter.add(file.getAbsolutePath());
}
}
}
Gridview
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/textView47"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"/>
you can use photoviwer library which is used to show full detail image on seperate activity .
// Any implementation of ImageView can be used!
mImageView = (ImageView) findViewById(R.id.iv_photo);
// Set the Drawable displayed
Drawable bitmap = getResources().getDrawable(R.drawable.wallpaper);
// or
// get your bitmap here
mImageView.setImageDrawable(bitmap);
// Attach a PhotoViewAttacher, which takes care of all of the zooming functionality.
// (not needed unless you are going to change the drawable later)
mAttacher = new PhotoViewAttacher(mImageView);
please refer below link
https://github.com/chrisbanes/PhotoView

Unable to set ImageView within GridView to Bitmap converted from Drawable

I have a GridView of ImageViews, and while I am building the GUI I currently want to convert some stock drawables into bitmaps, and set the ImageViews to these. They currently just come out as blanks, but as far as I can tell the code is along the correct lines.
The GridView XML: (it expands as more elements are added)
<com.example.tristan.studentshare.ExpandingGridView
android:id="#+id/achievement_grid"
android:layout_below="#+id/profile_details"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:columnWidth="100dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="4dp">
</com.example.tristan.studentshare.ExpandingGridView>
The row_grid_achievements XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageView
android:id="#+id/achievement_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="10dp"
android:src="#drawable/ic_person_black_24dp"/>
<TextView
android:id="#+id/achievement_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="20sp"/>
</LinearLayout>
The Achievement being displayed in the GridView:
public class Achievement {
private String id;
private String name;
private String description;
private Integer progress;
private Bitmap icon;
public Achievement(String id, String name, String description, Integer progress, Bitmap icon) {
this.id = id;
this.name = name;
this.description = description;
this.progress = progress;
this.icon = icon;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Integer getProgress() {
return progress;
}
public Bitmap getIcon() {
return icon;
}
}
The GridView adapter override:
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
public RecordHolder(TextView txtTitle, ImageView imageItem) {
this.txtTitle = txtTitle;
this.imageItem = imageItem;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder = null;
if (row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder(
(TextView)row.findViewById(R.id.achievement_text),
(ImageView)row.findViewById(R.id.achievement_image));
row.setTag(holder);
}
else holder = (RecordHolder)row.getTag();
Achievement achievement = data.get(position);
holder.txtTitle.setText(achievement.getName());
holder.imageItem.setImageBitmap(achievement.getIcon());
return row;
}
The implementation in the Activity:
ExpandingGridView gridView;
ArrayList<Achievement> gridArray = new ArrayList<Achievement>();
AchievementGridViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//TODO:Actual Achievement details from server
Bitmap icon = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_person_black_24dp);
for(int i = 0; i < 5; i++)
{
gridArray.add(new Achievement("0", "Achv" + i, "test", 50, icon));
}
gridView = (ExpandingGridView) findViewById(R.id.achievement_grid);
adapter = new AchievementGridViewAdapter(this, R.layout.row_grid_achievements, gridArray);
gridView.setAdapter(adapter);
}
The visual result:
The grid items should have an icon above them similar to the "profile picture"
In the getView() method of your adapter change the below line
holder.imageItem.setImageBitmap(achievement.getIcon());
according to below
holder.imageItem.setBackgroundDrawable(achievement.getIcon());
I hope it works
Firstly, instead of using GridView, I used RecyclerView, with a GridLayoutManager (http://blog.sqisland.com/2014/12/recyclerview-grid-with-header.html)
To have the elements I wanted displayed in the grid, the RecyclerView uses an Adapter and inflates each grid element with a custom layout, in the following link they use a CardView as the layout root (http://www.androidhive.info/2016/05/android-working-with-card-view-and-recycler-view/)
To get a Drawable instance from Resources, I use the following code:
Drawable d1 = ResourceCompat.getDrawable(getResources(), R.drawable.picture, null);
//or , depending on where your Drawable is,
Drawable d2 = ResourceCompat.getDrawable(getResources(), R.mipmap.picture, null);
In the code where it actually comes to setting the ImageView to a particular Drawable, I used the code:
//Using the Resource ID
myImageView.setImageResource(myResourceID);
//Using a Drawable instance
myImageView.setImageDrawable(myDrawable);
Note that in the AndroidHive link above, whichever of the the above two lines of code would be used in the adapter class, in the Overrided method 'onBindViewHolder'

Scrolling GridView causes GC_FOR_ALLOC free issues

I have a gridview with some images inside. Sometime when I'm scrolling, GC_FOR_ALLOC or heap is increased and I don't know why. I used a method to load a minimized image.
Might I use Picasso or a ViewHolder ? RecyclerView ?
The memory issues happened once or twice when I tested my app on my personal device although everything still ran. But on an older smartphone ( less efficient) , the memory issues totally stopped the phone and other apps from running.
I see warnings on my "setTag" as though the problem is caused by a memory leak.
How can I repair the memory problems ?
MainActivity.java
public class MainActivity extends Activity {
GridView gridView;
MediaPlayer mPlayer;
#Override
public synchronized void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean internetAcces = checkDataConnection();
if(internetAcces == true){
setContentView(R.layout.activity_main);
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest1 = new AdRequest.Builder().build();
adView.loadAd(adRequest1);
}
else{
setContentView(R.layout.activity_main2);
}
gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public synchronized void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
try{
if(mPlayer != null && mPlayer.isPlaying())
{
mPlayer.stop();
mPlayer.release();
playSong(position);
}
else
{
playSong(position);
}
}catch(Exception ex){
//Toast.makeText(MainActivity.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onPause(){
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
System.exit(0);
}
#Override
protected void onDestroy(){
super.onDestroy();
System.exit(0);
}
Here's MyAdapter.java
public final class MyAdapter extends BaseAdapter {
private final List<Item> mItems = new ArrayList<Item>(30);
private final LayoutInflater mInflater;
public Context context;
public MyAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
mItems.add(new Item("Hé pélo", R.drawable.hepelo));
mItems.add(new Item("Salut les losers", R.drawable.salutleslosers));
mItems.add(new Item("Arrête Abib", R.drawable.abib));
mItems.add(new Item("Goût bite", R.drawable.goutbite));
mItems.add(new Item("Makassy", R.drawable.makassy));
mItems.add(new Item("Joris Lecon", R.drawable.jorislecon));
mItems.add(new Item("Cache la drogue", R.drawable.cacheladrogue));
mItems.add(new Item("Un peu trop tactile", R.drawable.unpeutroptactile));
mItems.add(new Item("Qui c'est qu'a touché à Dorian ?", R.drawable.dorian));
mItems.add(new Item("T'es pas beau", R.drawable.tespasbeau));
mItems.add(new Item("Ta mère", R.drawable.tamere));
mItems.add(new Item("Je bute ce paquet de chips", R.drawable.jebutecepaquetdechips));
mItems.add(new Item("La maison du content", R.drawable.lamaisonducontent));
mItems.add(new Item("Mes péripétiiiiiies", R.drawable.mesperipeties));
mItems.add(new Item("La rapta babtou", R.drawable.laraptababtou));
mItems.add(new Item("Que vas-tu faire ?!", R.drawable.bangbang));
mItems.add(new Item("Oh les tétés !", R.drawable.lestetes));
mItems.add(new Item("Mollé mollé", R.drawable.laraptababtou));
mItems.add(new Item("Okéééé", R.drawable.ok));
mItems.add(new Item("Guillaume le thug", R.drawable.guillaumelethug));
mItems.add(new Item("C'est ma teub", R.drawable.cestmateub));
mItems.add(new Item("Je suis qu'un thug", R.drawable.jsuisquunthug));
}
#Override
public int getCount() {
return mItems.size();}
#Override
public Item getItem(int i) {
return mItems.get(i);
}
#Override
public long getItemId(int i) {
return mItems.get(i).drawableId;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if (v == null) {
v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = getItem(i);
//picture.setImageResource(item.drawableId);
picture.setImageBitmap(decodeSampledBitmapFromResource(context.getResources(),item.drawableId, 150, 150));
name.setText(item.name);
return v;}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
private static class Item {
public final String name;
public final int drawableId;
Item(String name, int drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
}
main_activity.xml :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:verticalSpacing="0dp"
android:layout_weight="1"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"
android:listSelector="#android:color/transparent"
android:scrollingCache="false"
android:animationCache="false"
/>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
ads:adSize="SMART_BANNER"
ads:adUnitId="ca-app-pub-2373549811754777/2717783647"
/>
grid_item.xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.slamingresources.laboiteamisterv.SquareImageView
android:id="#+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
/>
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="4dp"
android:paddingBottom="5dp"
android:layout_gravity="bottom"
android:textColor="#android:color/white"
android:background="#55000002"
/>
Logcat :
11-20 03:21:45.878: I/dalvikvm-heap(16815): Clamp target GC heap from 128.451MB to 128.000MB
11-20 03:21:47.628: I/dalvikvm-heap(16815): Clamp target GC heap from 135.930MB to 128.000MB
11-20 03:21:47.688: D/dalvikvm(16815): GC_BEFORE_OOM freed 109065K, 85% free 20521K/131004K, paused 59ms, total 60ms
11-20 03:22:00.498: D/dalvikvm(16815): GC_FOR_ALLOC freed 3972K, 85% free 20494K/131004K, paused 24ms, total 24ms
I know this is old but for those that are still looking for same answers: you can use getcachedir() to store data temporarily in Android.
For more options see Android data storage.
Yes, you got this error! Why? AFAIK, before Android 3.0 (I dont remember exactly) bitmap is not auto recycle. You must recycle bitmap after not using it.
To resolve your problem, I suggest you cache your Bitmap. When cached hit, recycle unused one.
Edit: I think the easiest way to solve your problem is use another library to help loading image. You can look at Universal ImageLoader. There's a function which can help you load with target size:
// Load image, decode it to Bitmap and return Bitmap synchronously
ImageSize targetSize = new ImageSize(80, 50); // result Bitmap will be fit to this size
Bitmap bmp = imageLoader.loadImageSync(imageUri, targetSize, options);

How to display fancy frame on the image in android viewpager/imageview?

I have developed an app that is suppose to display images located in the drawable folder. I used imageview/viewpager for it. However, I would like to display frame shown below.On the top of the image so that image appears more fancy.. Also, the frame should swipe along with the image...so that it looks more beautiful... I was thinking of creating it permanently on the image...through photoshop... But I didn't like that idea ..So I thought may be android have something for it....I am android beginner...So any code help along with explanation will be appreciated..Following are my codes..
Mainactivity.java
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
public class MainActivity extends Activity {
MediaPlayer oursong;
ViewPager viewPager;
ImageAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(0);
oursong.start();
viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(MyViewPagerListener);
}
private int pos = 0;
#Override
protected void onPause() {
super.onPause();
if(oursong != null){
pos = oursong.getCurrentPosition();
oursong.release();
oursong = null;
}
}
#Override
protected void onResume(){
super.onResume();
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.seekTo(pos); // You will probably want to save an int to restore here
oursong.start();
}
private final OnPageChangeListener MyViewPagerListener = new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
if (pos == adapter.getCount() - 1){
// adding null checks for safety
if(oursong != null){
oursong.pause();
}
} else if (!oursong.isPlaying()){
// adding null check for safety
if(oursong != null){
oursong.start();
}
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
};
}
Imageadapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.four,
R.drawable.five
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
activity_main.xml
<RelativeLayout 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"
tools:context=".MainActivity"
android:icon="#drawable/icon" >
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:icon="#drawable/icon" />
<ImageView
android:id="#+id/swipe_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="#drawable/swipe_left" />
<ImageView
android:id="#+id/swipe_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#drawable/swipe_right" />
</RelativeLayout>
Edited
Hidden portion of the image under frame
You can do it using a LayerDrawable
A Drawable that manages an array of other Drawables. These are drawn
in array order, so the element with the largest index will be drawn on
top.
You have two choices to use LayerDrawable.You can either define it in a separate drawable xml and then simply set the image in your ImageView, or you can configure a LayerDrawable dynamically in your code.
Programmatically using code
Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.yourImage);;
layers[1] = r.getDrawable(R.drawable.yourFrame);
LayerDrawable layerDrawable = new LayerDrawable(layers);
imageView.setImageDrawable(layerDrawable);
Now you have your ImageView having two images(1.your image and 2.Frame) set on it.
Edit :
In your ImageAdapter, you need to modify instantiateItem(ViewGroup container, int position) something like
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
Resources r = context.getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(GalImages[position]);
layers[1] = r.getDrawable(R.drawable.yourFrame);
LayerDrawable layerDrawable = new LayerDrawable(layers);
imageView.setImageDrawable(layerDrawable);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
Edit 2
As some portions of your image gets hidden under the frame, you need to set the width and height of your image before using it in the ImageView.Have some calculations of what could be the best width and height combination for your image, such that it will fit exactly with your frame.For setting height and width of your image
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
Resources r = context.getResources();
Bitmap bmp = BitmapFactory.decodeResource(r, GalImages[position]);
int width=200;//set your width
int height=200;//set your height
Bitmap resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height, true);
Drawable d = new BitmapDrawable(r,resizedbitmap);
Drawable[] layers = new Drawable[2];
layers[0] = d;
layers[1] = r.getDrawable(R.drawable.yourFrame);
LayerDrawable layerDrawable = new LayerDrawable(layers);
imageView.setImageDrawable(layerDrawable);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
Using XML
Create a new Drawable XML file, let's call it mylayer.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/yourimage" />
<item android:drawable="#drawable/yourframe" />
</layer-list>
Now in your Activity set the image using that Drawable:
imageView.setImageDrawable(getResources().getDrawable(R.layout.mylayer));
I hope this gives you the basic idea for achieving what you want.

Popup gridview cell onTOuch

I have a grid View In which I am adding Button dynamically.
I am setting OnTouch listener to grid view.
I want when my finger move on the particular cell then that cell element should get popup
similar way our android keyboard do.
public class MainActivity extends Activity {
private ArrayList<Integer> data;
private GridView gv;
private TextView biggerView = null;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createData();
gv = (GridView) findViewById(R.id.grid);
gv.setNumColumns(10);
gv.setAdapter(new FilterButtonAdapter(data, this));
gv.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
try {
int position = gv.pointToPosition((int) event.getX(),
(int) event.getY());
View v = (View) gv.getChildAt(position);
if (v != null) {
gv.requestFocus();
gv.setSelection(gv.pointToPosition( (int)
event.getX(), (int) event.getY()));
}
return true;
} catch (Exception e) {
return true;
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
int position = gv.pointToPosition((int) event.getX(),
(int) event.getY());
View v = (View) gv.getChildAt(position);
if (v != null) {
gv.clearFocus();
TextView tv = (TextView) v.findViewById(R.id.texttoadd);
Toast.makeText(MainActivity.this, tv.getText(),
Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
}
});
}
private void createData() {
data = new ArrayList<Integer>();
for (int i = 0; i < 200; i++) {
data.add(i);
}
}
enter code here
i have write this code which is giving me the selected item but when item are more then grid is scrolled and after that the am not getting the item which i am selecting
i have figured out that the x and y position is getting change when grid is scrolled
i may be wrong
please help
I think that suggested in the question way of touch position detection might be not effective, because there's more high-level way to obtain scrolling position.
The main ideas of the implementation are the following:
Use onScrollChanged() to track scroll position at every moment;
Display selection as separate view above GridView;
Track if selected item is visible (using this question);
So, to obtain proper scroll callback, slightly customized GridView is needed:
public class ScrollAwareGridView extends GridView {
/** Callback interface to report immediate scroll changes */
public interface ImmediateScrollListener {
void onImmediateScrollChanged();
}
/** External listener for */
private ImmediateScrollListener mScrollListener = null;
public ScrollAwareGridView(final Context context) {
super(context);
}
public ScrollAwareGridView(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public ScrollAwareGridView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onScrollChanged(final int l, final int t, final int oldl, final int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (null != mScrollListener) {
mScrollListener.onImmediateScrollChanged();
}
}
/**
* #param listener {#link ImmediateScrollListener}
*/
public void setImmediateScrollListener(final ImmediateScrollListener listener) {
mScrollListener = listener;
}
}
It will be placed in the xml the following way (main.xml):
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.TestApp.ScrollAwareGridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3" />
<!-- Selection view -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/selectedImage"
android:visibility="gone" />
</RelativeLayout>
In above xml there's also selection view presented.
Activity will handle selection of items (however, it might be better to keep selection and scroll tracking logic in separate object (grid adapter or specific grid fragment) in order not to keep grid-specific logic in Activity code):
public class MyActivity extends Activity implements ScrollAwareGridView.ImmediateScrollListener, AdapterView.OnItemClickListener {
private static final String TAG = "MyActivity";
/** To start / pause music */
private ImageView mSelectedImage = null;
/** position of selected item in the adapter */
private int mSelectedPosition;
/** Main grid view */
private ScrollAwareGridView mGrid;
/** Adapter for grid view */
private ImageAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Show the layout with the test view
setContentView(R.layout.main);
mSelectedImage = (ImageView) findViewById(R.id.selectedImage);
mGrid = (ScrollAwareGridView) findViewById(R.id.grid);
if (null != mGrid) {
mAdapter = new ImageAdapter(this);
mGrid.setAdapter(mAdapter);
mGrid.setImmediateScrollListener(this);
mGrid.setOnItemClickListener(this);
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
mSelectedImage.setImageBitmap(null);
mSelectedImage.setVisibility(View.GONE);
mSelectedPosition = -1;
}
#Override
public void onImmediateScrollChanged() {
if (mSelectedPosition >= 0) {
int firstPosition = mGrid.getFirstVisiblePosition(); // This is the same as child #0
int wantedChild = mSelectedPosition - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= mGrid.getChildCount()) {
Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
mSelectedImage.setVisibility(View.INVISIBLE);
return;
} else {
mSelectedImage.setVisibility(View.VISIBLE);
}
// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.
final View selectedView = mGrid.getChildAt(wantedChild);
if (null != selectedView && mSelectedImage.getVisibility() == View.VISIBLE) {
// Put selected view on new position
final ViewGroup.MarginLayoutParams zoomedImageLayoutParams = (ViewGroup.MarginLayoutParams) mSelectedImage.getLayoutParams();
// 200 is difference between zoomed and not zoomed images dimensions
// TODO: Avoid hardcoded values and use resources
final Integer thumbnailX = mGrid.getLeft() + selectedView.getLeft() - (ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION - ImageAdapter.GRID_ITEM_DIMENSION) / 2;
final Integer thumbnailY = mGrid.getTop() + selectedView.getTop() - (ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION - ImageAdapter.GRID_ITEM_DIMENSION) / 2;
zoomedImageLayoutParams.setMargins(thumbnailX,
thumbnailY,
0,
0);
mSelectedImage.setLayoutParams(zoomedImageLayoutParams);
}
}
}
#Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
mSelectedPosition = position;
final Bitmap bm = mAdapter.getImage(position);
// Obtain image from adapter, with check if image presented
if (bm != null) {
final ViewGroup.MarginLayoutParams zoomedImageLayoutParams = (ViewGroup.MarginLayoutParams) mSelectedImage.getLayoutParams();
// 200 is difference between zoomed and not zoomed images dimensions
// TODO: Avoid hardcoded values and use resources
final Integer thumbnailX = mGrid.getLeft() + view.getLeft() - (ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION - ImageAdapter.GRID_ITEM_DIMENSION) / 2;
final Integer thumbnailY = mGrid.getTop() + view.getTop() - (ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION - ImageAdapter.GRID_ITEM_DIMENSION) / 2;
zoomedImageLayoutParams.setMargins(thumbnailX,
thumbnailY,
0,
0);
zoomedImageLayoutParams.height = ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION;
zoomedImageLayoutParams.width = ImageAdapter.HIGHLIGHTED_GRID_ITEM_DIMENSION;
mSelectedImage.setImageBitmap(bm);
mSelectedImage.setScaleType(ImageView.ScaleType.CENTER);
mSelectedImage.setLayoutParams(zoomedImageLayoutParams);
mSelectedImage.setVisibility(View.VISIBLE);
}
}
}
Below is GridViews adapter. However there's nothing specific in it which related to scrolling tracking (most of code I've reused from this answer):
public class ImageAdapter extends BaseAdapter {
private static final String TAG = "ImageAdapter";
/** For creation of child ImageViews */
private Context mContext;
public static final Integer[] IMAGES_RESOURCES = {
R.drawable.image001, R.drawable.image002, R.drawable.image003, R.drawable.image004,
R.drawable.image005, R.drawable.image006, R.drawable.image007, R.drawable.image008,
R.drawable.image009, R.drawable.image010, R.drawable.image011, R.drawable.image012,
R.drawable.image013, R.drawable.image014, R.drawable.image015, R.drawable.image016,
R.drawable.image017, R.drawable.image018, R.drawable.image019, R.drawable.image020,
R.drawable.image021, R.drawable.image022, R.drawable.image023, R.drawable.image024,
R.drawable.image025, R.drawable.image026, R.drawable.image027, R.drawable.image028,
R.drawable.image029, R.drawable.image030, R.drawable.image031, R.drawable.image032,
R.drawable.image033, R.drawable.image034, R.drawable.image035, R.drawable.image036,
R.drawable.image037, R.drawable.image038, R.drawable.image039, R.drawable.image040,
R.drawable.image041, R.drawable.image042, R.drawable.image043, R.drawable.image044,
R.drawable.image045, R.drawable.image046, R.drawable.image047, R.drawable.image048,
R.drawable.image049, R.drawable.image050
};
// TODO: use resources for that sizes, otherwise You'll GET PROBLEMS on other displays!
public final static int GRID_ITEM_DIMENSION = 300;
public final static int HIGHLIGHTED_GRID_ITEM_DIMENSION = 500;
private Bitmap mHolder = null;
private static final int CACHE_SIZE = 50 * 1024 * 1024; // 8 MiB cache
/** Cache to store all decoded images */
private LruCache<Integer, Bitmap> mBitmapsCache = new LruCache<Integer, Bitmap>(CACHE_SIZE) {
#Override
protected int sizeOf(final Integer key, final Bitmap value) {
return value.getByteCount();
}
#Override
protected void entryRemoved(final boolean evicted, final Integer key, final Bitmap oldValue, final Bitmap newValue) {
if (!oldValue.equals(mHolder)) {
oldValue.recycle();
}
}
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
mHolder = BitmapFactory.decodeResource(c.getResources(), R.drawable.ic_launcher, null);
}
#Override
public int getCount() {
return IMAGES_RESOURCES.length;
}
#Override
public Object getItem(int position) {
return IMAGES_RESOURCES[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(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(GRID_ITEM_DIMENSION, GRID_ITEM_DIMENSION));
} else {
imageView = (ImageView) convertView;
}
final Bitmap itemBitmap = mBitmapsCache.get(IMAGES_RESOURCES[position]);
if (itemBitmap == null || itemBitmap.isRecycled()) {
Log.e(TAG, position + " is missed, launch decode for " + IMAGES_RESOURCES[position]);
imageView.setImageBitmap(mHolder);
mBitmapsCache.put(IMAGES_RESOURCES[position], mHolder);
new BitmapWorkerTask(mBitmapsCache, mContext.getResources(), this).execute(IMAGES_RESOURCES[position]);
} else {
Log.e(TAG, position + " is here for " + IMAGES_RESOURCES[position]);
imageView.setImageBitmap(itemBitmap);
}
return imageView;
}
/**
* Obtains image at position (if there's only holder, then null to be returned)
*
* #param position int position in the adapter
*
* #return {#link Bitmap} image at position or null if image is not loaded yet
*/
public Bitmap getImage(final int position) {
final Bitmap bm = mBitmapsCache.get(IMAGES_RESOURCES[position]);
return ((mHolder.equals(bm) || bm == null) ? null : bm.copy(Bitmap.Config.ARGB_8888, false));
}
/** AsyncTask for decoding images from resources */
static class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private int data = 0;
private final LruCache<Integer, Bitmap> mCache;
private final Resources mRes;
private final BaseAdapter mAdapter;
public BitmapWorkerTask(LruCache<Integer, Bitmap> cache, Resources res, BaseAdapter adapter) {
// nothing to do here
mCache = cache;
mRes = res;
mAdapter = adapter;
}
// Decode image in background.
#Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
// Use sizes for selected bitmaps for good up-scaling
return decodeSampledBitmapFromResource(mRes, data, GRID_ITEM_DIMENSION, GRID_ITEM_DIMENSION);
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
mCache.put(data, bitmap);
mAdapter.notifyDataSetChanged();
}
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
options.outHeight = GRID_ITEM_DIMENSION;
options.outWidth = GRID_ITEM_DIMENSION;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
}

Categories

Resources