I need to create and set customize bitmap image on each row of listview. I am doing that using picasso. My code inside getView of adapter is like below,
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
View rowView = convertView;
if (rowView == null){
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.horizontal_listview_list_sample, parent, false);
viewHolder = new ViewHolder();
viewHolder.imgDot = (ImageView) rowView.findViewById(R.id.rowIcon);
viewHolder.rowIconBackround = (ImageView) rowView.findViewById(R.id.rowIconBackground);
rowView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) rowView.getTag();
}
//Start Custom Image View///////
String photoUrl1 = arrayList.get(position).getPhotoUrl();
if (photoUrl1.length()<8){
photoUrl1 = "SOME_URL";
}
final String photoUrl = photoUrl1;
final ImageView imgDot = viewHolder.imgDot;
// final viewHolder.imgDot = (ImageView) rowView.findViewById(R.id.rowIcon);
final View finalRowView = rowView;
final ViewHolder finalViewHolder = viewHolder;
final Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap2, Picasso.LoadedFrom from) {
Log.d("PICASO", " called: " + "onBitmapLoaded called");
Bitmap original;
original = new MyProfile().getResizedBitmap(bitmap2, (int) new MainActivity().dipToPixels(MainActivity.getInstance(), 63), (int) new MainActivity().dipToPixels(MainActivity.getInstance(), 63));
BitmapDrawable bitmap = (BitmapDrawable) finalRowView.getResources().getDrawable(R.drawable.drawer_pro_pic_placeholder);
int bitmapHeight= bitmap .getBitmap().getHeight();
int bitmapWidth = bitmap .getBitmap().getWidth();
Bitmap mask = BitmapFactory.decodeResource(finalRowView.getResources(), R.drawable.drawer_pro_pic_placeholder);
Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(), Bitmap.Config.ARGB_8888);
Canvas mCanvas = new Canvas(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
int width = mask.getWidth();
int height = mask.getHeight();
float centerX = (width - original.getWidth()) * 0.5f;
float centerY = (height- original.getHeight()) * 0.5f;
mCanvas.drawBitmap(original, centerX, centerY, null);
mCanvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);
imgDot.getLayoutParams().height = bitmapHeight;
imgDot.getLayoutParams().width = bitmapWidth;
imgDot.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgDot.setImageBitmap(result);
imgDot.setAdjustViewBounds(true);
Picasso.with(context).cancelRequest(finalViewHolder.imgDot);
targets.remove(this);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.d("PICASO", " called: " + "onBitmapFailed called");
Picasso.with(context).cancelRequest(finalViewHolder.imgDot);
targets.remove(this);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.d("PICASO", "responseForRegistration called: " + "onPrepareLoad called");
}
};
targets.add(target);
// imgDot.setTag(target);
Picasso.with(context).load(photoUrl).into(target);
//End Custom Image View////////////
return rowView;
}
Suppose, there is two row so two customize bitmap will be created. When first one is created its showing nice but when second one created then this last image is showing in both row's imageview.
What I need to change in my code?
Any help will be appreciated.
You could try something by creating handler as subclass of your adapter and passing specific reference of your view holder and position which will help us to avoid overriding issue of target listener
// construct the handler inside your adapter's constructor so you know it is on the UI thread
Handler myHandler = new Handler();
class LoadImage implements Runnable {
ImageView iv;
int position;
public LoadImage(ImageView iv, int position) {
this.iv = iv;
this.position = position;
}
#Override
public void run() {
// keep your target listener stuffs here
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap2, Picasso.LoadedFrom from) {
Log.d("PICASO", " called: " + "onBitmapLoaded called");
Bitmap original;
original = new MyProfile().getResizedBitmap(bitmap2, (int) new MainActivity().dipToPixels(MainActivity.getInstance(), 63), (int) new MainActivity().dipToPixels(MainActivity.getInstance(), 63));
BitmapDrawable bitmap = (BitmapDrawable) finalRowView.getResources().getDrawable(R.drawable.drawer_pro_pic_placeholder);
int bitmapHeight= bitmap .getBitmap().getHeight();
int bitmapWidth = bitmap .getBitmap().getWidth();
Bitmap mask = BitmapFactory.decodeResource(finalRowView.getResources(), R.drawable.drawer_pro_pic_placeholder);
Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(), Bitmap.Config.ARGB_8888);
Canvas mCanvas = new Canvas(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
int width = mask.getWidth();
int height = mask.getHeight();
float centerX = (width - original.getWidth()) * 0.5f;
float centerY = (height- original.getHeight()) * 0.5f;
mCanvas.drawBitmap(original, centerX, centerY, null);
mCanvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);
iv.getLayoutParams().height = bitmapHeight;
iv.getLayoutParams().width = bitmapWidth;
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setImageBitmap(result);
iv.setAdjustViewBounds(true);
Picasso.with(context).cancelRequest(iv);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.d("PICASO", " called: " + "onBitmapFailed called");
Picasso.with(context).cancelRequest(iv);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.d("PICASO", "responseForRegistration called: " + "onPrepareLoad called");
}
};
Picasso.with(context).load(photoList.get(position)).into(target);
}
}
And you will call it from your getView by :
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
View rowView = convertView;
if (rowView == null){
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.horizontal_listview_list_sample, parent, false);
viewHolder = new ViewHolder();
viewHolder.imgDot = (ImageView) rowView.findViewById(R.id.rowIcon);
viewHolder.rowIconBackround = (ImageView) rowView.findViewById(R.id.rowIconBackground);
rowView.setTag(viewHolder);
//Change is here
viewHolder.mRunnable = new LoadImage(viewHolder.imgDot, position);
}else {
viewHolder = (ViewHolder) rowView.getTag();
//Change is here
myHandler.removeCallbacks(viewHolder.mRunnable);
}
//Start Custom Image View///////
String photoUrl1 = arrayList.get(position).getPhotoUrl();
if (photoUrl1.length()<8){
photoUrl1 = "SOME_URL";
}
final String photoUrl = photoUrl1;
final ImageView imgDot = viewHolder.imgDot;
// final viewHolder.imgDot = (ImageView) rowView.findViewById(R.id.rowIcon);
final View finalRowView = rowView;
final ViewHolder finalViewHolder = viewHolder;
//Change is here
myHandler.postDelayed(viewHolder.mRunnable, 3000);
return rowView;
}
Related
I have a GridView where I add images directly with ImageView (I don't use an XML for the image). Now, I want to add image name at the bottom of each cell using a TextView. How can I do it? Thanks in advance.
Custom Adapter Class:
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
private GridView imageCarrete;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth, GridView imageCarrete) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
this.imageCarrete = imageCarrete;
}
#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);
// Listener del GridView
imageCarrete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Intent i = new Intent(_activity, FullScreenViewActivity.class);
i.putExtra("position", position);
_activity.startActivityForResult(i, 1234);
}
});
return imageView;
}
/*
* 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;
}
public void remove(String path){
_filePaths.remove(path);
}
}
GridView XML
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:gravity="center"
android:stretchMode="columnWidth"
android:background="#000000">
</GridView>
Within your getView() method, replace your ImageView with a TextView with a drawable:
TextView tv = new TextView(context);
tv.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
you will supply the drawable to the top and 0 to the rest, ie:
tv.setCompoundDrawablesWithIntrinsicBounds(0, yourDrawable, 0, 0);
Just create a LinearLayout as you are creating Imagview in getView() method... add ImageView and TextView to it with addView() method.... have a look ..
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout _ll;
if (convertView == null) {
_ll = new LinearLayout(mContext);
_ll.setOrientation(LinearLayout.VERTICAL);
ImageView img = new ImageView(mContext);
img.setLayoutParams(new LinearLayout.LayoutParams(100, 100)); // your image size
img.setBackgroundResource(images[position]); // here pass your array list position
_ll.addView(img);
TextView text = new TextView(mContext);
text.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
text.setText("dsaf");
text.setGravity(Gravity.CENTER);
_ll.addView(text);
} else {
_ll = (LinearLayout) convertView;
}
return _ll;
}
You can also use RelativeLayout if you want to overlay your text over image..
I am using Picasso library to load images into ImageView, Like i have only one item in a ListView, so its showing progress loader even image has been downloaded successfully and visible in ImageView.
So how may i do control over it ?
viewHolder.progressBar.setVisibility(View.VISIBLE);
Picasso.with(MainActivity.this)
.load(imageURL) // web image URL
.fit().centerInside()
.transform(transformation)
.error(R.drawable.ic_launcher)
.placeholder(R.drawable.ic_launcher)
.rotate(90)
.into(viewHolder.imageViewReport , new Callback() {
#Override
public void onSuccess() {
// TODO Auto-generated method stub
viewHolder.progressBar.setVisibility(View.GONE);
}
#Override
public void onError() {
// TODO Auto-generated method stub
viewHolder.progressBar.setVisibility(View.GONE);
}
});
Usually, I am facing this issue for the first list item ...
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// convert view = design
View view = convertView;
if (view == null) {
viewHolder = new ViewHolder();
view = layoutInflater.inflate(Resource, null);
viewHolder.imageView = (ImageView) view.findViewById(R.id.imageView);
viewHolder.progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
final Transformation transformation = new Transformation() {
#Override
public Bitmap transform(Bitmap source) {
int targetWidth = viewHolder.imageViewReport.getWidth();
double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
int targetHeight = (int) (targetWidth * aspectRatio);
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
if (result != source) {
// Same bitmap is returned if sizes are the same
source.recycle();
}
return result;
}
#Override
public String key() {
// TODO Auto-generated method stub
return null;
}
};
I have gridview and have to download images to gridview. When I open app I cannot see any images, but I think my code is somehow correct. How to fix it?
I use this code in my adapter:
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
//float wd = 250 / Resources.getSystem().getDisplayMetrics().density;
//float hg = 300 / Resources.getSystem().getDisplayMetrics().density;
int pxwd = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 90, Resources.getSystem().getDisplayMetrics());
int pxhg = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 120, Resources.getSystem().getDisplayMetrics());
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(pxwd, pxhg));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageDrawable(LoadImageFromURL(GridViewConfig.getImage_list().get(position)));
return imageView;
}
// references to our images
private Drawable LoadImageFromURL(String url)
{
try {
InputStream is = (InputStream) new URL(url).getContent();
return Drawable.createFromStream(is, "src");
} catch (Exception e) {
return null;
}
}
and here is url list:
public class GridViewConfig {
public static ArrayList<String> image_listGrid = new ArrayList<String>();
public static ArrayList<String> getImage_list() {
return image_listGrid;
}
public static void setImage_list(ArrayList<String> image_list) {
GridViewConfig.image_listGrid = image_list;
}
public static void addImageUrls(){
image_listGrid.add("someimage.jpg");
}
But problem is no image is showing on my GridView.
In your getView(...), you should use TypedValue.COMPLEX_UNIT_DIP replaces TypedValue.COMPLEX_UNIT_SP:
int pxwd = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 90, Resources.getSystem().getDisplayMetrics());
int pxhg = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 120, Resources.getSystem().getDisplayMetrics());
Hope this help!
I'm working on getting image from the camera and gallery. I'm trying to get the bitmap of the image to reduce the size of the image. But the bitmapfactory is null when I tried debugging the process. I'm not understanding why it is so even for absolute uri. I'm implementing inside adapter.
#SuppressLint("ResourceAsColor")
public class PSAdapter extends BaseAdapter{
private Context mContext;
private ArrayList<Message> mMessages;
public PSAdapter(Context context, ArrayList<Message> messages) {
super();
this.mContext = context;
this.mMessages = messages;
}
#Override
public int getCount() {
return mMessages.size();
}
#Override
public Object getItem(int position) {
return mMessages.get(position);
}
#SuppressWarnings("deprecation")
#SuppressLint("ResourceAsColor")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Message message = (Message) this.getItem(position);
ViewHolder holder;
if(convertView == null)
{
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.sms, parent, false);
holder.message = (TextView) convertView.findViewById(R.id.message_text);
holder.picture = (ImageView) convertView.findViewById(R.id.chat_image);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
if(message.message==null){
holder.message.setVisibility(View.GONE);
holder.picture.setVisibility(View.VISIBLE);
Bitmap attachment = getScaledBitmap("content://media/external/images/media/4391", 800, 800);
holder.picture.setImageBitmap(attachment);
}else{
holder.message.setVisibility(View.VISIBLE);
holder.picture.setVisibility(View.GONE);
holder.message.setText(message.getMessage());
}
LayoutParams lp = (LayoutParams) holder.message.getLayoutParams();
if(message.isStatusMessage())
{
holder.message.setBackgroundDrawable(null);
lp.gravity = Gravity.LEFT;
holder.message.setTextColor(R.color.textFieldColor);
}
else
{
if(message.isMine())
{
holder.message.setBackgroundResource(R.drawable.speech_bubble_green);
lp.gravity = Gravity.RIGHT;
}
else
{
holder.message.setBackgroundResource(R.drawable.speech_bubble_orange);
lp.gravity = Gravity.LEFT;
}
holder.message.setLayoutParams(lp);
holder.message.setTextColor(R.color.textColor);
}
return convertView;
}
public static class ViewHolder
{
TextView message;
ImageView picture;
}
#Override
public long getItemId(int position) {
return 0;
}
private Bitmap getScaledBitmap(String picPath, int width, int height){
BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
sizeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picPath,sizeOptions);
int inSampleSize = imageSize(sizeOptions, width, height);
sizeOptions.inJustDecodeBounds = false;
sizeOptions.inSampleSize = inSampleSize;
return BitmapFactory.decodeFile(picPath, sizeOptions);
}
private int imageSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
final int height = options.outHeight;
final int width = options.outWidth;
int size = 1;
if(height>reqHeight || width>reqWidth){
final int heightRatio = Math.round((float)height/(float)reqHeight);
final int widthRatio = Math.round((float)width/(float)reqWidth);
size = heightRatio<widthRatio? heightRatio:widthRatio;
}
return size;
}
}
I am new to android. I am displaying images in gridview by using AsyncTask. But there are some issues like:
1: onScroll AsyncTask tasks gets call again.
2: Images are not displaying correctly ( Once I scroll it shows top image and load the original latter).
here is my code:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ListRowHolder listRowHolder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.ll_sponsor_list_item,
parent, false);
listRowHolder = new ListRowHolder();
listRowHolder.imgSponsor = (ImageView) convertView
.findViewById(R.id.imggrid_item_image);
convertView.setTag(listRowHolder);
} else {
listRowHolder = (ListRowHolder) convertView.getTag();
}
try {
task = new BitmapWorkerTask(listRowHolder.imgSponsor);
task.image_path = ImageName.get(position);
task.execute(1);
} catch (Exception e) {
if (thisLogger != null) {
thisLogger.error(e.toString());
thisLogger.error("\r\n");
}
}
return convertView;
}
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String image_path;
public BitmapWorkerTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(Integer... params) {
try {
while (running) {
Bitmap picture = BitmapFactory.decodeFile(image_path);
int width = picture.getWidth();
int height = picture.getHeight();
float aspectRatio = (float) width / (float) height;
int newWidth = 98;
int newHeight = (int) (98 / aspectRatio);
Log.v("ImageList", "L");
return picture = Bitmap.createScaledBitmap(picture,
newWidth, newHeight, true);
}
} catch (Exception e) {
if (thisLogger != null) {
thisLogger.error(e.toString());
thisLogger.error("\r\n");
}
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
Please let me know whats wrong here.