initialize RelativeLayout in this getView, programmatic view generation - android

I am using a getView in an adapter where I am creating an imageview and making that equal to convertView where the view has already been initialized before. It contains image thumbnails, some of which represent videos.
#Override
public View getView(int position, View convertView, ViewGroup container) {
// First check if this is the top row
if (position < mNumColumns) {
if (convertView == null) {
convertView = new View(mContext);
}
// Set empty view with height of ActionBar
//convertView.setLayoutParams(new AbsListView.LayoutParams(
// LayoutParams.MATCH_PARENT, mActionBarHeight));
return convertView;
}
// Now handle the main ImageView thumbnails
ImageView imageView;
if (convertView == null) { // if it's not recycled, instantiate and initialize
imageView = new RecyclingImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(mImageViewLayoutParams);
} else { // Otherwise re-use the converted view
imageView = (ImageView) convertView;
}
// Check the height matches our calculated column width
if (imageView.getLayoutParams().height != mItemHeight) {
imageView.setLayoutParams(mImageViewLayoutParams);
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
if(images.get(position - mNumColumns).getUriString().contains("video")){
//display video icon
}
else
{
//don't display video icon
}
// Finally load the image asynchronously into the ImageView, this also takes care of
// setting a placeholder image while the background thread runs
if (images != null && !images.isEmpty())
mImageFetcher.loadImage(images.get(position - mNumColumns).getUriString()/*.imageUrls[position - mNumColumns]*/, imageView);
return imageView;
}
The thumbnails do not have a "play" button on them to designate that they are videos, so in those cases I need to add a play button, programmatically.
Typically I use a viewholder pattern with an inflated layout, I am not doing that in this case because I actually don't want some things in memory.
So instead I want to programmatically make a RelativeLayout as the root view of each cell (mRelativeLayout = (RelativeLayout)convertView) and add the imageview and playbutton imageview into that convertview
How do I do that? It requires modification of this statement but I'm not sure how to initialize all the re-used views
} else { // Otherwise re-use the converted view
imageView = (ImageView) convertView;
}

I think the best approach here would be to use an Adapter that returns different types of views (by overriding getViewTypeCount() and getItemViewType()), for example as described in this answer.
That way you do not need to programmatically alter the returned views, at all. Just define two XML layouts and inflate/reuse either one or the other according to whether the item at that position has a video or not.
Not only would this be clearer, you wouldn't have the performance penalty of "transforming" one view into the other whenever a video-row is supplied as convertView for another item without one, or vice-versa

I would make your getView() always return a RelativeLayout object (which I call containerView below) to which you add your ImageView(s) as children.
The only complication here is that you need to give these children identifiers so that you can retrieve them from a recycled convertView later. Note that I used the built-in, static View.generateViewId() for this, which is API level 17. If you need it to work pre-API-level-17 you can create your own ids using unique integers (such as 1, 2, etc.) -- just make sure they aren't greater than 0x0FFFFFF. Update: I added code that I use for this below.
See the comments I added in several points below.
#Override
public View getView(int position, View convertView, ViewGroup container) {
// First check if this is the top row
if (position < mNumColumns) {
if (convertView == null) {
convertView = new View(mContext);
}
// Set empty view with height of ActionBar
//convertView.setLayoutParams(new AbsListView.LayoutParams(
// LayoutParams.MATCH_PARENT, mActionBarHeight));
return convertView;
}
// Now handle the main ImageView thumbnails
RelativeLayout containerView;
ImageView imageView;
ImageView videoIconView; // TODO: or whatever type you want to use for this...
if (convertView == null) { // if it's not recycled, instantiate and initialize
containerView = new RelativeLayout(mContext);
// TODO: The layout params that you used for the image view you probably
// now want to use for the container view instead...
imageView.setLayoutParams(mImageViewLayoutParams); // If so, you can change their name...
imageView = new RecyclingImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//imageView.setLayoutParams(mImageViewLayoutParams); // This probably isn't needed any more.
// Generate an Id to use for later retrieval of the imageView...
// This assumes it was initialized to -1 in the constructor to mark it being unset.
// Note, this could be done elsewhere in this adapter class (such as in
// the constructor when mImageId is initialized, since it only
// needs to be done once (not once per view) -- I'm just doing it here
// to avoid having to show any other functions.
if (mImageId == -1) {
mImageId = View.generateViewId();
}
imageView.setId(mImageId);
containerView.addView(imageView, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
// NOTE: At this point, I would personally always just add the video icon
// as a child of containerView here no matter what (generating another unique
// view Id for it, mVideoIconId, similar to how was shown above for the imageView)
// and then set it to either VISIBLE or INVISIBLE/GONE below depending on whether
// the URL contains the word "video" or not.
// For example:
vidoIconView = new <whatever>;
// TODO: setup videoIconView with the proper drawable, scaling, etc. here...
if (mVideoIconId == -1) {
mVideoIconId = View.generateViewId();
}
videoIconView.setId(mVideoIconId);
containerView.addView(videoIconView, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
final RelativeLayout.LayoutParams layout = ((RelativeLayout.LayoutParams)containerView.getLayoutParams());
layout.addRule(RelativeLayout.LayoutParams.CENTER_HORIZONTAL); // ... or whatever else you want
layout.addRule(RelativeLayout.LayoutParams.ALIGN_PARENT_BOTTOM); // ... or whatever else you want
} else {
// Otherwise re-use the converted view
containerView = (RelativeLayout) convertView;
imageView = containerView.findViewById(mImageId);
videoIconView = containerView.findViewById(mVideoIconId); // see comment above
}
// Check the height matches our calculated column width
if (containerView.getLayoutParams().height != mItemHeight) {
containerView.setLayoutParams(mImageViewLayoutParams);
}
if(images.get(position - mNumColumns).getUriString().contains("video")){
//display video icon
// see comment above, here you can probably just do something like:
videoIconView.setVisibility(View.VISIBLE);
}
else
{
//don't display video icon
videoIconView.setVisibility(View.GONE); // could also use INVISIBLE here... up to you.
}
// Finally load the image asynchronously into the ImageView, this also takes care of
// setting a placeholder image while the background thread runs
if (images != null && !images.isEmpty())
mImageFetcher.loadImage(images.get(position - mNumColumns).getUriString()/*.imageUrls[position - mNumColumns]*/, imageView);
return containerView;
}
Update:
In response the question in the comments, I use something like this (in my custom "ViewController" base class):
private static int s_nextGeneratedId = 1;
/**
* Try to do the same thing as View.generateViewId() when using API level < 17.
* #return Unique integer that can be used with setId() on a View.
*/
protected static int generateViewId() {
// AAPT-generated IDs have the high byte nonzero; clamp to the range under that.
if (++s_nextGeneratedId > 0x00FFFFFF)
s_nextGeneratedId = 1; // Roll over to 1, not 0.
return s_nextGeneratedId;
}
Note that you do not need a unique view id for every single cell in your grid. Rather, you just need it for each type of child view that you might want to access using findViewById(). So in your case, you're probably going to need just two unique ids. Since the view ids auto-generated from your xml layout files into your R.java typically are very large, I've found it convenient just to use low numbers for my hand-generated ids (as shown above).

Related

Android Listview scroll lag with view holder

I have noticed that a ListView in my application has started to stutter quite badly all of a sudden.
I am using Volley to load images for my listview items - downloading and caching the images are fine and scroll smooth as butter.
However I currently have a spinner that sits on top of the NetworkImageView while I wait for the image to load. The lag comes in once the image has successfully loaded - I set the spinner to be invisible and the image to visible. Changing the visibility of these items seems to be the source of the lag.
I am currently using the View Holder pattern, my onResponseLoad looks like the following:
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null){ //Check that the image is not null
ProgressBar progress = holder.getProgress(); //Find Spinner - this doesnt cause lag
progress.setVisibility(View.GONE); //Hide spinner (This causes lag)
img.setVisibility(View.VISIBLE); //Image is a network image from the holder (This causes lag)
}
}
(Note that commenting out those two offending lines results in buttery smooth scrolling again)
The other strange thing is that I haven't touched this part of the application in some time and in my current live version, as well as previous commits there is no lag. Comparing my current code base to previous non-lagging versions show that there has been 0 change to the code surrounding this aspect of the application. Furthermore other lists that I have implemented using almost the exact same technique have not experienced this issue.
The only thing I can think of that could be different is that I am now using the latest version of Gradle - although I don't think that should have an impact at run-time.
I am at a total loss as to what is going on, would appreciate any insight on what I should be doing to achieve smooth ListView scrolling (or what may have lead to my implementation's degradation)
EDIT: Posting code of getView() as requested
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View placeSelectorView = convertView;
PlaceViewHolder placeSelectorHolder = null;
if(placeSelectorView == null){ //If we are creating the row for the first time
LayoutInflater inflater = (LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //Inflate the view
placeSelectorView = inflater.inflate(R.layout.place_selector, parent, false); //Get the view
placeSelectorHolder = new PlaceViewHolder(placeSelectorView); //Create holder object
placeSelectorView.setTag(placeSelectorHolder); //Attach reference to the view
}else{
placeSelectorHolder = (PlaceViewHolder) placeSelectorView.getTag(); //Load holder from memory
if(!placeSelectorHolder.isHasImage()){ //Need to optimise this
placeSelectorHolder.getLayout().addView(placeSelectorHolder.getrLayoutThumbnail(), 0);
placeSelectorHolder.setHasImage(true);
}
if(!placeSelectorHolder.isSpinnerVisible()){
placeSelectorHolder.getProgressBar().setVisibility(View.VISIBLE);
placeSelectorHolder.getPlaceImg().setVisibility(View.GONE);
placeSelectorHolder.setSpinnerVisible(true);
}
}
POI place = (values.get(position)); //Get POI object for the place
POI parentPlace = getParent(place); //Get parent POI for place
placeSelectorHolder.getPlaceName().setText(place.getName());
if(parentPlace != null){ //If place has a parent POI
placeSelectorHolder.getParentPlaceName().setText(parentPlace.getName());
}else{ //We don't want the parent text in the view
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) placeSelectorHolder.getParentPlaceName().getLayoutParams();
layoutParams.weight = 0; //Setting weight to 0 will remove it from the LinearLayout
placeSelectorHolder.getParentPlaceName().setLayoutParams(layoutParams);
}
final PlaceViewHolder holder = placeSelectorHolder;
loadThumbnail(holder, place);
return placeSelectorView;
}
public void loadThumbnail(final PlaceViewHolder placeSelectorHolder, POI place){
RealmList<poiPhoto> photos = place.getPhotos();
String mUrl;
if(!photos.isEmpty()){
mUrl = photos.get(0).getSmall();
}else{
mUrl = "";
}
final NetworkImageView placeImg = placeSelectorHolder.getPlaceImg();
if(!mUrl.equals("")){ //If there is an Image Available
ImageLoader imageLoader = ServerSingleton.getInstance(getContext()).getImageLoader(); //Get volley imageloader from Singleton
imageLoader.get(mUrl, new ImageLoader.ImageListener() { //Custom get so we can use override onResponse and OnErrorResponse
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null){ //Check that the image is not null
ProgressBar progressBar = placeSelectorHolder.getProgressBar(); //Find Spinner
placeImg.setVisibility(View.VISIBLE);
if(progressBar != null) progressBar.setVisibility(View.GONE); //Make the spinner invisible
placeSelectorHolder.setSpinnerVisible(false);
}
}
#Override
public void onErrorResponse(VolleyError error) {
//TO-DO: Get an error image
}
});
placeImg.setImageUrl(mUrl, imageLoader); //Send the request
placeSelectorHolder.setHasImage(true);
}else{ //There is no image
LinearLayout layout = placeSelectorHolder.getLayout(); //Find the horizontal layout
layout.removeView(placeSelectorHolder.getrLayoutThumbnail()); //Remove the Thumbnail layout
placeSelectorHolder.setHasImage(false);
}
}

Change gravity programmatically on ListView item

I would like to have a ListView in which some items render on the left, and some on the right. I don't really know how to make this happen though. I was thinking of calling setGravity(Gravity.RIGHT) on the View my adapter's getView() method returns, but that method apparently exists only for ViewGroup, which makes me think it would actually change the gravity of the object's contents. It would look something like this:
getView(int position, View toReturn, ViewGroup parent) {
// Holder pattern, *yawn*
if (needsToBeOnRight) {
toReturn.setGravity(Gravity.RIGHT)
// or whatever it is I'm actually supposed to do
}
return toReturn;
}
The View represented by toReturn is expected to be a RelativeLayout, so I supppose in theory I could cast it to one and try the above, but as discussed above, I doubt that will work. How should I proceed?
Turns out I was almost there. In order to make it work, I had to wrap the view I want to right-or-left-orient in a FrameLayout. That would make toReturn in the above code a FrameLayout.
ViewHolder holder = (ViewHolder) toReturn.getTag();
// Get the view's LayoutParams. In this case, since it is wrapped by a FrameLayout,
// that is the type of LayoutParams necessary.
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) holder.viewThatMightNeedToBeOnRight.getLayoutParams();
// Set gravity to right or left as necessary within the LayoutParams.
if (params != null) {
if (needsToBeOnRight) {
params.gravity = Gravity.RIGHT;
} else {
params.gravity = Gravity.LEFT;
}
// Assign the newly edited LayoutParams to the view.
holder.viewThatMightNeedToBeOnRight.setLayoutParams(params);
}
LayoutParams lay = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
lay.gravity = Gravity.END;
mListView.setLayoutParams(lay);

Listview style Each Row

this is the code in my custom adapter (THE CODE IN BROWN COLOR) when initially list is build proper margin is applied to valid items when i scroll down and again scroll up all the rows in list shifts the margin left by 20 what i'm doing wrong please reply soon
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
// getting data
final ViewMovieDetailsModel_ViewComments movies = getItem(position);
if (convertView == null)
{
convertView = View.inflate(context, R.layout.comment_row, null);
holder = new ViewHolder();
//getting handles
holder.comments_linearLayout = (LinearLayout) convertView.findViewById(R.id.comments_linearLayout);
holder.commenter_textView = (TextView) convertView.findViewById(R.id.comment_row_commenter);
holder.commented_on_textView = (TextView) convertView.findViewById(R.id.comment_row_comment_time);
holder.comment_text_textView = (TextView) convertView.findViewById(R.id.comment_row_comment_text);
holder.reply_button = (Button) convertView.findViewById(R.id.comment_row_reply_button);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
if (movies != null)
{
if (((movies.getParent_comment_id()).toString().equals("null")) && session.isLoggedIn()==true) {
holder.reply_button.setVisibility(View.VISIBLE);
}else{
holder.reply_button.setVisibility(View.INVISIBLE);
}
`if (!((movies.getParent_comment_id()).toString().equals("null")))
{
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
params.setMargins(20, 0, 0, 0);
holder.comments_linearLayout.setLayoutParams(params);
}`
holder.commenter_textView.setText(movies.getUsername_commentor());
holder.commenter_textView.setTag(movies.getUser_id_commentor());
return convertView;
}
because you are setting margins (the brown font) in 'if' statement:
if (movies != null)
just take it out of this if block (for example put it just before the return point)
Right now this code is probably not executed at the first view load, since the movie is null. When the getView is called second time, the movie is not null, and the marigin is set according to your 'brown' code.
if this is not the solution - maybe the inside if statement condition is not true (the one that is in first 'brown' row). so.. your own logic prevents the marigins to be set as you want :)
Please let me know if it helps.
One way you could go about solving this problem is instead of using LayoutParams.setMargins(20, 0, 0, 0), you could create an empty TextView whose width is 20 dp by default and whose position will be to the left of your rows contents. It will be View.GONE by default, but when if (!((movies.getParent_comment_id()).toString().equals("null"))) happens, you can set that to View.VISIBLE

Setting ImageView width and height before drawing in a ListView adapter

I have an adapter to a ListView is a list of ImageViews. I am using a stretch to make the image fil the imageview so I can take smaller images and make them larger on the screen, however the ImageView normally just uses wrap_content and this is an issue because the images just show up as their normal width and height. Is there any way I can set the height and width of a view before drawing it because as in this case I do not have control over the view after it has been drawn. Here is my aapter method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String currentImage = getItem(position);
ScaleType scaleType = ScaleType.FIT_CENTER;
float screenWidth = parent.getResources().getDisplayMetrics().widthPixels;
if (convertView == null) {
convertView = new ImageView(parent.getContext());
}
// WHAT I WOULD LIKE TO BE ABLE TO DO, but this returns null pointer exception
// convertView.getLayoutParams().width = (int) screenWidth;
// convertView.getLayoutParams().height = (int) ((float)(screenWidth/currentImage.getWidth())*currentImage.getHeight());
((ImageView) convertView).setScaleType(scaleType);
((ImageView) convertView).setImageBitmap(MainActivity.cache.getBitmap(currentImage));
return convertView;
}
How about something like someView.setHeight() and someView.setWidth()? Or someView.setLayoutParams()? You could add either of these to the overridden getView() callback and it should take care of your problem.
You could also Create a Custom View and override something like getMeasuredWidthAndState(). (I think that's one of the right methods, but I'm not one hundred percent sure.) You could create a width class variable and a height class variable that all instances of your custom ImageView would use. However, that might be a bit much if you just want to set the layout width and height though.

ListView: convertView / holder getting confused

I'm working with a ListView, trying to get the convertView / referenceHolder optimisation to work properly but it's giving me trouble. (This is the system where you store the R.id.xxx pointers in as a tag for each View to avoid having to call findViewById). I have a ListView populated with simple rows of an ImageView and some text, but the ImageView can be formatted either for portrait-sized images (tall and narrow) or landscape-sized images (short and wide). It's adjusting this formatting for each row which isn't working as I had hoped.
The basic system is that to begin with, it inflates the layout for each row and sets the ImageView's settings based on the data, and includes an int denoting the orientation in the tag containing the R.id.xxx values. Then when it starts reusing convertViews, it checks this saved orientation against the orientation of the new row. The theory then is that if the orientation is the same, then the ImageView should already be set up correctly. If it isn't, then it sets the parameters for the ImageView as appropriate and updates the tag.
However, I found that it was somehow getting confused; sometimes the tag would get out of sync with the orientation of the ImageView. For example, the tag would still say portrait, but the actual ImageView would still be in landscape layout. I couldn't find a pattern to how or when this happened; it wasn't consistent by orientation, position in the list or speed of scrolling. I can solve the problem by simply removing the check about convertView's orientation and simply always set the ImageView's parameters, but that seems to defeat the purpose of this optimisation.
Can anyone see what I've done wrong in the code below?
static LinearLayout.LayoutParams layoutParams;
(...)
public View getView(int position, View convertView, ViewGroup parent){
ReferenceHolder holder;
if (convertView == null){
convertView = inflater.inflate(R.layout.pick_image_row, null);
holder = new ReferenceHolder();
holder.getIdsAndSetTag(convertView, position);
if (data[position][ORIENTATION] == LANDSCAPE) {
// Layout defaults to portrait settings, so ImageView size needs adjusting.
// layoutParams is modified here, with specific values for width, height, margins etc
holder.image.setLayoutParams(layoutParams);
}
holder.orientation = data[position][ORIENTATION];
} else {
holder = (ReferenceHolder) convertView.getTag();
if (holder.orientation != data[position][ORIENTATION]){ //This is the key if statement for my question
switch (image[position][ORIENTATION]) {
case PORTRAIT:
// layoutParams is reset to the Portrait settings
holder.orientation = data[position][ORIENTATION];
break;
case LANDSCAPE:
// layoutParams is reset to the Landscape settings
holder.orientation = data[position][ORIENTATION];
break;
}
holder.image.setLayoutParams(layoutParams);
}
}
// and the row's image and text is set here, using holder.image.xxx
// and holder.text.xxx
return convertView;
}
static class ReferenceHolder {
ImageView image;
TextView text;
int orientation;
void getIdsAndSetTag(View v, int position){
image = (ImageView) v.findViewById(R.id.pickImageImage);
text = (TextView) v.findViewById(R.id.pickImageText);
orientation = data[position][ORIENTATION];
v.setTag(this);
}
}
Thanks!
Rather than putting orientation as a data member of ReferenceHolder, examine the actual LayoutParams of the ImageView to see what orientation it is in. This way, by definition, you can't get out of sync somehow.
To be honest, I'm confused by the code you have there, as you never seem to change layoutParams, which would seem to be kinda important. Or, shouldn't you have layoutParamsPortrait and layoutParamsLandscape or something? To me, it looks like the rules are:
If it's portrait and the row is initially created, leave it portrait
Everything else is landscape, regardless of what the orientation flag says, since you always set it to layoutParams, which is presumably landscape

Categories

Resources