Android Gridview not obeying vertical spacing - android

My code produces gridview with only horizontal spacing but no vertical spacing. Can't find the problem even after searching google. I only get the vertical spacing if i add padding to the imageview, but it doesn't give me the required spacing. Here is my code, i use universal image loader:
public PhotoGridFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the individual image size in the grid and the grid image spacing
mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.empty_photo)
.showImageForEmptyUri(R.drawable.empty_photo)
.showImageOnFail(R.drawable.empty_photo)
.cacheInMemory(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
mAdapter = new ImageAdapter(getActivity());
if(((MainActivity)getActivity()).isRunningFirstTime) {
}
}
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.photo_grid_fragment, container, false);
final GridView mGridView = (GridView) v.findViewById(R.id.gridview);
mGridView.setAdapter(mAdapter);
mGridView.setOnItemClickListener(this);
mGridView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), false, true));
// This listener is used to get the final width of the GridView and then calculate the
// number of columns and the width of each column. The width of each column is variable
// as the GridView has stretchMode=columnWidth. The column width is used to set the height
// of each view so we get nice square thumbnails.
mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#SuppressWarnings("deprecation")
#TargetApi(VERSION_CODES.JELLY_BEAN)
#Override
public void onGlobalLayout() {
if (mAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(
mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));
if (numColumns > 0) {
final int columnWidth =
(mGridView.getWidth() / numColumns) - mImageThumbSpacing;
columnNum = numColumns;
mAdapter.setNumColumns(numColumns);
mAdapter.setItemHeight(columnWidth);
if (Utils.hasJellyBean()) {
mGridView.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
} else {
mGridView.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
}
}
}
});
return v;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#TargetApi(VERSION_CODES.JELLY_BEAN)
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
final Intent i = new Intent(getActivity(), PhotoDetailActivity.class);
i.putExtra(PhotoDetailActivity.EXTRA_IMAGE, (photoIds[position - columnNum]));
if (Utils.hasJellyBean()) {
// makeThumbnailScaleUpAnimation() looks kind of ugly here as the loading spinner may
// show plus the thumbnail image in GridView is cropped. so using
// makeScaleUpAnimation() instead.
ActivityOptions options =
ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight());
getActivity().startActivity(i, options.toBundle());
} else {
startActivity(i);
}
}
public int getCurTab() {
return getArguments().getInt(CURRENT_TAB);
}
public static PhotoGridFragment newInstance(int position, int curTab) {
PhotoGridFragment photoGrid = new PhotoGridFragment();
Bundle categoryId = new Bundle();
categoryId.putInt(CATEGORY_ID, position);
categoryId.putInt(CURRENT_TAB, curTab);
photoGrid.setArguments(categoryId);
return photoGrid;
}
/**
* The main adapter that backs the GridView. This is fairly standard except the number of
* columns in the GridView is used to create a fake top row of empty views as we use a
* transparent ActionBar and don't want the real top row of images to start off covered by it.
*/
private class ImageAdapter extends BaseAdapter {
private final Context mContext;
private int mItemHeight = 0;
private int mNumColumns = 0;
private GridView.LayoutParams mImageViewLayoutParams;
public ImageAdapter(Context context) {
super();
mContext = context;
mImageViewLayoutParams = new GridView.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
#Override
public int getCount() {
// If columns have yet to be determined, return no items
if (getNumColumns() == 0) {
return 0;
}
// Size + number of columns for top empty row
return photoIds.length;
}
#Override
public Object getItem(int position) {
return photoIds[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public View getView(int position, View convertView, ViewGroup container) {
// Now handle the main ImageView thumbnails
ImageView imageView;
if (convertView == null) { // if it's not recycled, instantiate and initialize
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(mImageViewLayoutParams);
} else { // Otherwise re-use the converted view
imageView = (ImageView) convertView;
}
if ((imageView.getLayoutParams().height != mItemHeight)
|| (imageView.getLayoutParams().width != mItemHeight))
{
imageView.setLayoutParams(mImageViewLayoutParams);
}
// Finally load the image asynchronously into the ImageView, this also takes care of
// setting a placeholder image while the background thread runs
ImageLoader.getInstance()
.displayImage(photoIds[position], imageView, options);
return imageView;
//END_INCLUDE(load_gridview_item)
}
/**
* Sets the item height. Useful for when we know the column width so the height can be set
* to match.
*
* #param height
*/
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
mImageViewLayoutParams =
new GridView.LayoutParams(mItemHeight, mItemHeight);
notifyDataSetChanged();
}
public void setNumColumns(int numColumns) {
mNumColumns = numColumns;
}
public int getNumColumns() {
return mNumColumns;
}
}
}
Gridview xml:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="#dimen/image_thumbnail_size"
android:horizontalSpacing="#dimen/image_thumbnail_spacing"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="#dimen/image_thumbnail_spacing"
android:drawSelectorOnTop="true"
android:listSelector="#drawable/photogrid_list_selector" />

Spent 6 hours trying to find the problem. Now i have the solution. The problem was the 1dp spacing was not showing on ldpi devices but was showing on mdpi, xhdpi, etc. I just created a "values-ldpi" folder and create a dimens.xml folder then added the dimension image_thumbnail_spacing and assigned it to 2dp and its working now. Thanks

Related

How can I manipulate certain elements of a ListView and scroll the view manually without weird things to happen?

So basically my goal is to have a ListView filled with large icons which i want to scroll to the previous or next item by clicking a corresponding button. Furthermore I want to highlight (Set the alpha from 30% to 100%) the icon which is currently at top of the screen.
Unfortunately some weird things happen when I try to accomplish this. At first, everything works fine. When I click the next button, the list scrolls (by setSelection) to the next element and set the Alpha of the highest element to 100%. But after the third time clicking "next", suddenly not only the highest but also the element below gets an alpha of 100%. From then on all the elements are set to 100% alpha. However if I go up and click the previous button everything works fine also after the third time clicking.
The setting of the highlighted icon happens in the method highlightPreselectedEmoji() in the activity EmojiSelectionActivity. This method is call from within the button listeners prevBtn.setOnClickListener and nextBtn.setOnClickListener. To get the view item which should be highlighted I defined the function getViewByPosition(int pos) in the activity class.
Here the screen how it looks when it works fine:
ListView with icons and highlighted first icon
This is how it shouldn't look:
ListView error all icons highlighted
This is the code of the activity:
public class EmojiSelectionActivity extends AppCompatActivity {
private EmojisAdapter emojisAdapter;
private EmojisManager emojisManager;
private ListView emojisContainer;
private Button prevBtn;
private Button nextBtn;
private int currentPosition;
private int previousPosition;
private Activity context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emoji_selection);
Intent intent = getIntent();
emojisManager = EmojisManager.getInstance(getApplicationContext());
String detectedEmojiUnicode = intent.getStringExtra("DetectedEmoji");
emojisManager.setDetectedTags(detectedEmojiUnicode);
emojisAdapter = new EmojisAdapter(this, emojisManager.getEmojisByTags());
currentPosition = 0;
previousPosition = 0;
initUI();
loadEmojis();
highlightPreselectedEmoji();
}
/**
* Init the UI elements & listeners
*/
private void initUI(){
prevBtn = (Button) findViewById(R.id.btn_previous_emoji);
nextBtn = (Button) findViewById(R.id.btn_next_emoji);
emojisContainer = (ListView) findViewById(R.id.emojisContainer);
//Set listeners
emojisContainer.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Emoji selectedEmoji = emojisAdapter.getItem(position);
returnToDetectionActivity(selectedEmoji.getUnicodeId());
}
});
prevBtn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
if(currentPosition > 0){
currentPosition --;
if(currentPosition <= 0){
prevBtn.setVisibility(View.INVISIBLE);
}else{
prevBtn.setVisibility(View.VISIBLE);
}
}
nextBtn.setVisibility(View.VISIBLE);
highlightPreselectedEmoji();
//getViewByPosition(emojisContainer.getFirstVisiblePosition()).setAlpha(1.0f);
}
});
nextBtn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
if(currentPosition < emojisContainer.getAdapter().getCount() - 1 ){
currentPosition ++;
if(currentPosition >= emojisContainer.getAdapter().getCount() -1){
nextBtn.setVisibility(View.INVISIBLE);
}else{
nextBtn.setVisibility(View.VISIBLE);
}
}
prevBtn.setVisibility(View.VISIBLE);
highlightPreselectedEmoji();
//emojisContainer.smoothScrollToPosition(currentPosition);
//emojisContainer.setSelection(currentPosition);
}
});
}
/**
* Set the currently preselected emoji to an opacity of 100% and the old preselected back to 30% opacity
*/
private void highlightPreselectedEmoji(){
Log.d("EMOJISELECTION", "*************************scrolling to position: " + currentPosition);
emojisContainer.setSelection(currentPosition);
emojisContainer.post(new Runnable() {
#Override
public void run() {
//emojisContainer.smoothScrollToPosition(currentPosition); //Android bug not scrolling properly
emojisContainer.getFirstVisiblePosition();
emojisContainer.setItemChecked(currentPosition, true);
//emojisAdapter.notifyDataSetChanged();
getViewByPosition(previousPosition).setAlpha(0.3f);
Log.d("EMOJISELECTION", "set back transparent previous position: " + previousPosition);
//emojisContainer.findViewById(R.id.img_emoji).setAlpha(0.4f);
getViewByPosition(currentPosition).setAlpha(1.0f);
Log.d("EMOJISELECTION", "set highlight current position: " + currentPosition);
//emojisContainer.getChildAt(currentPosition).setAlpha(1.0f);
previousPosition = currentPosition;
}
});
}
/**
* Get the view item element of ListView by given position
* #param pos : position in list
* #return : view element accroding to the position
*/
private View getViewByPosition(int pos) {
try {
final int firstListItemPosition = emojisContainer.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + emojisContainer.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition ) {
return emojisAdapter.getView(pos, null, emojisContainer);
} else {
final int childIndex = pos - firstListItemPosition;
return emojisContainer.getChildAt(childIndex);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This is the Layout with the ListView:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background_gradient">
<com.example.plucinst.emojat.CustomButton
style="#style/buttonBlackTransparent"
android:id="#+id/btn_previous_emoji"
android:layout_marginTop="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:text="#string/button_previous_caption"
/>
<ListView
android:id="#+id/emojisContainer"
android:paddingTop="72dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:transcriptMode="alwaysScroll">
</ListView>
<com.example.plucinst.emojat.CustomButton
android:layout_marginBottom="16dp"
android:id="#+id/btn_next_emoji"
style="#style/buttonBlackTransparent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:text="#string/button_next_caption"
/>
</RelativeLayout>
That's the ListView view item:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:paddingLeft="32dp"
android:paddingRight="32dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:alpha="0.3">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
android:src="#drawable/clown_face"
android:id="#+id/img_emoji"/>
This is the BaseAdapter:
public class EmojisAdapter extends BaseAdapter {
private final List<Emoji> emojiList;
private Activity context;
private int emojiDpPaddingSize;
private final float scale;
public EmojisAdapter(Activity context, ArrayList<Emoji> emojiList){
this.context = context;
this.emojiList = emojiList;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String paddingSizeString = sharedPrefs.getString("pref_emoji_size", "0");
switch (paddingSizeString){
case "0":
emojiDpPaddingSize = 0;
break;
case "32":
emojiDpPaddingSize = 32;
break;
case "64":
emojiDpPaddingSize = 64;
break;
default:
emojiDpPaddingSize = 0;
break;
}
scale = context.getResources().getDisplayMetrics().density;
}
#Override
public int getCount() {
if (emojiList != null) {
return emojiList.size();
} else {
return 0;
}
}
#Override
public Emoji getItem(int position) {
if (emojiList != null) {
return emojiList.get(position);
} else {
return null;
}
}
#Override
public long getItemId(int position) {
return position;
}
public void add(Emoji emoji) {
emojiList.add(emoji);
}
public void add(List<Emoji> emojis) {
emojiList.addAll(emojis);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
EmojisAdapter.ViewHolder holder;
Emoji emoji = getItem(position);
String emojiUnicode = emoji.getUnicodeId();
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = vi.inflate(R.layout.list_item_emoji, null);
holder = createViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (EmojisAdapter.ViewHolder) convertView.getTag();
}
//holder.viewEmojiIcon.setLayerType(View.LAYER_TYPE_SOFTWARE,null);
//holder.viewEmojiIcon.setdpTextSize(190);
//holder.viewEmojiIcon.setIcon(emojiUnicode, true);
int imgId = context.getResources().getIdentifier(emoji.getImgName(), "drawable", context.getPackageName());
holder.viewEmojiIcon.setImageResource(imgId);
int paddingInPixels = (int) (emojiDpPaddingSize *scale + 0.5f);
int currentPaddingLeftInPixels = (int) (16 *scale + 0.5f);
int currentPaddingRightInPixels = (int) (16 *scale + 0.5f);
int paddingTop = holder.viewEmojiIcon.getPaddingTop();
int paddingBottom = holder.viewEmojiIcon.getPaddingBottom();
holder.viewEmojiIcon.setPadding(currentPaddingLeftInPixels + paddingInPixels ,paddingTop,currentPaddingRightInPixels + paddingInPixels,paddingBottom);
//Log.d("EMOJISELECTION", "TextView text" + viewEmojiIcon.getText());
return convertView;
}
private EmojisAdapter.ViewHolder createViewHolder(View v) {
EmojisAdapter.ViewHolder holder = new EmojisAdapter.ViewHolder();
holder.viewEmojiIcon = (ImageView) v.findViewById(R.id.img_emoji);
return holder;
}
private static class ViewHolder {
public ImageView viewEmojiIcon;
}
}

Dynamically add images to Android WheelView

I have been working on this issue for days now. I am using the kankan Android wheel example/library, but am wanting to dynamically add images to the wheel when a button is pressed. The image added depends on the button's text. It seems like a fairly easy task, but perhaps I am missing something. I tried calling the adapter's notifyDataChangedEvent() after passing and adding the selected image to the adapter's list of cached images. Debugging has showed that the images were being added to the list of images, but they are not showing up on the wheel. If someone could please help me out with this problem I would appreciate it!
Code:
public void addItem(String text) {
for(Item c: Item.values()){
if(c.getName().equals(text)) {
slotMachineAdapter.addImage(c.getImage());
break;
}
}
slotMachineAdapter.notifyDataChangedEvent();
}
Adapter
private class SlotMachineAdapter extends AbstractWheelAdapter {
// Image size
final int IMAGE_WIDTH = 700;
final int IMAGE_HEIGHT = 150;
// Slot machine symbols
private final int items[] = new int[] {
R.mipmap.ic_flipper
};
// Cached images
private List<SoftReference<Bitmap>> images;
// Layout inflater
private Context context;
/**
* Constructor
*/
public SlotMachineAdapter(Context context) {
this.context = context;
images = new ArrayList<SoftReference<Bitmap>>();
for (int id : items) {
images.add(new SoftReference<Bitmap>(loadImage(id)));
}
}
/**
* Loads image from resources
*/
private Bitmap loadImage(int id) {
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id);
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
bitmap.recycle();
return scaled;
}
#Override
public int getItemsCount() {
return items.length;
}
// Layout params for image view
final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
ImageView img;
if (cachedView != null) {
img = (ImageView) cachedView;
} else {
img = new ImageView(context);
}
img.setLayoutParams(params);
SoftReference<Bitmap> bitmapRef = images.get(index);
Bitmap bitmap = bitmapRef.get();
if (bitmap == null) {
bitmap = loadImage(items[index]);
images.set(index, new SoftReference<Bitmap>(bitmap));
}
img.setImageBitmap(bitmap);
return img;
}
//Adds image to list of images
public void addImage(int img){
images.add(new SoftReference<Bitmap>(loadImage(img)));
}
}
Because the count you return referenced to items variable, But addImage function did not change items size. Try to change your code like below and test it again:
#Override
public int getItemsCount() {
return images.size();
}

Android banner ads not displaying in Listview as expected

I'm attempting to create a listview which has banner ads at every nth interval. In my code, it's every 6 items. I've based my code on the example here. The example provided is based on having a banner ad at the first and last of the listview, so I've encountered problems when trying to intersperse the banner ads within the listview at equal intervals. Specifically, my ads don't display every 6th time. The result I have from the code below is displaying two consecutive ads at positions 7,8 and then my third at position 13. I'm not sure what could be causing the ad at position 8 to appear.
Any idea how I can fix this?
Code below...
Firstly, the creation of my SimpleCursorAdapter, which contains about 14 strings to display in the listview in this case.
// Create and populate listview
final ListView listview = (ListView) findViewById(android.R.id.list);
// SimpleCursorAdapter method
Cursor c = dbh.getAllCategoriesCursor();
startManagingCursor(c);
String[] from = new String[] { "name" };
int[] to = new int[] { R.id.category_label};
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.rowlayout, c, from, to, 0);
setListAdapter(new ListViewAdapter(this, cursorAdapter));
And here is my ListViewAdapter, extending the BaseAdapter class
public class ListViewAdapter extends BaseAdapter {
private Activity mContext;
private SimpleCursorAdapter listAdapter;
private LayoutInflater mLayoutInflater;
private int k = 6; // interval ad every 6 items
int baseItems;
int noAds; // used for listview offset
// Constructor takes in a BaseAdapter
public ListViewAdapter(Activity activity, SimpleCursorAdapter delegate) {
mContext = activity;
listAdapter = delegate;
baseItems = listAdapter.getCount();
noAds = baseItems / k;
mLayoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// Total count includes list items and ads.
return baseItems + noAds;
}
#Override
public Object getItem(int position) {
// Return null if an item is an ad. Otherwise return the delegate item.
if (isItemAnAd(position)) {
return null;
}
return listAdapter.getItem(getOffsetPosition(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return listAdapter.getViewTypeCount() + noAds;
}
#Override
public int getItemViewType(int position) {
if (isItemAnAd(position)) {
return listAdapter.getViewTypeCount();
} else {
return listAdapter.getItemViewType(getOffsetPosition(position));
}
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (!isItemAnAd(position)) && listAdapter.isEnabled(getOffsetPosition(position));
}
private boolean isItemAnAd(int position) {
// Place an ad at the first and last list view positions.
// -- should override for every kth positions
if (position == 0) return false;
// Calculate offsets caused by ads already embedded
int offset = 0;
if (position > k){
int div = position / k;
offset = div;
}
return ((position-offset) % k == 0);
}
// Get the position that is offset by the insertion of the ads
private int getOffsetPosition(int position) {
return position - noAds;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Display every n list items
if (isItemAnAd(position)) {
if (convertView instanceof AdView) {
// Don’t instantiate new AdView, reuse old one
return convertView;
} else {
// Create a new AdView
AdView adView = new AdView(getApplicationContext());
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(BANNER_AD_ID);
// Disable focus for sub-views of the AdView to avoid problems with
// trackpad navigation of the list.
for (int i = 0; i < adView.getChildCount(); i++)
{
adView.getChildAt(i).setFocusable(false);
}
adView.setFocusable(false);
// Convert the default layout parameters so that they play nice with
// ListView.
float density = getApplicationContext().getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
height);
adView.setLayoutParams(params);
AdRequest bannerIntermediateReq = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("d9e108ab") //means that a test ad is shown on my phone
.build();
adView.loadAd(bannerIntermediateReq);
return adView;
}
} else {
// Offload displaying other items to the delegate
return listAdapter.getView(position - (int) Math.ceil(position / k),
convertView, parent);
}
}
}
Update 9/6... Found a workaround of sorts that creates an ad at the nth interval, followed by all following ads at n-1 intervals. So if I set n=8 I'll get an ad inserted after 8 list items, after ads inserted every 7 items after that. I'm quite happy to settle for this given the amount of time I've sunk into it. It's probably an off-by-one bug somewhere that I cannot find whatsoever. Hope this helps someone at some point. Here's the modifications:
private boolean isItemAnAd(int position) {
if (position < k) return false;
// Calculate current offset caused by ads already embedded
if (position==k){
return true;
}
else {
return isItemAnAd(position-k);
}
}
and
// Get the position that is offset by the insertion of the ads
private int getOffsetPosition(int position) {
int currentNoAds = position / k;
return position - currentNoAds;
}
and, in getView...
return listAdapter.getView(getOffsetPosition(position) ,
convertView, parent);

Changing an image in a gridview when clicked, when certain other criteria are met

How to change an image in my specific gridview as I get the below error. I have followed similar examples elsewhere without success. ie I get "cannot change from integer to imageview" when trying the below, from
(see Android GridView - update View based on position), i.e.:
int tempid = v.getId();
ImageView imgView = FruitToChooseFromImages.get(tempid);
imgView.setBackgroundResource(R.drawable.blank);
I have also tried:
{ // remove viewable image / make blank
ImageView imageView = (ImageView) v;
imageView.setImageResource(R.drawable.blank);
}
FULL CODE BELOW IF YOU NEED IT:
Main JAVA code:
public class game1mainscreen extends Activity {
private MyGridviewAdapter1 mAdapter;
private GridView gridview;
private ArrayList<Integer> FruitToChooseFromImages;
private ArrayList<Integer> tempintarray;
int Totalfruit = 11; // starting from 0 of course (so an 11=12 fruit) this means there are 6 pairs of fruit to select
int fruitleft = 12;
int fruitstilltoadd = Totalfruit + 1;
int numberOfFruitToRemove = 6;
int puthere = 0;
int imagesSelectedThusFar = 0;
int Fruitleft = 0;
int firstfruitselected = R.drawable.blank; int firstfruitselpos;
int secondfruitselected = R.drawable.blank; int secondfruitselpos;
int removefirstimage = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameonemenu);
{
FruitToChooseFromImages = new ArrayList<Integer>();
FruitToChooseFromImages.add(R.drawable.fruit0);
.....etc....
FruitToChooseFromImages.add(R.drawable.fruit11);
}
...code removed which randomly sorts FruitToChooseFromImages (ie arraylist of images) into 6 duplicate pairs of images...
// prepared arraylist is passed to the Adapter class
mAdapter = new MyGridviewAdapter1(this, FruitToChooseFromImages);
// Set custom adapter to gridview
gridview = (GridView) findViewById(R.id.gridView1);
gridview.setAdapter(mAdapter);
// DO THIS WHEN CLICKED
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
int fruitselected = (int)FruitToChooseFromImages.get(position);
// start
if (fruitselected == R.drawable.blank)
{
// if blank/empty icon clicked on then DO NOTHING
}
else
{ // firstly, say fruit name
int soundtoplaynow = getrightsound(position, fruitselected);
SoundManager.playSound(soundtoplaynow, 1);
// next
if (imagesSelectedThusFar == 0)
{
imagesSelectedThusFar = 1;
firstfruitselected = fruitselected; firstfruitselpos = position;
//both switch fruit image to blank in the array and display blank at position clicked
FruitToChooseFromImages.set(position, R.drawable.blank);
{ // remove viewable image / make blank
ImageView imageView = (ImageView) v;
imageView.setImageResource(R.drawable.blank);
}
}
else // so two images have been selected! do they match?
{
imagesSelectedThusFar = 0; // has reached 2, so reset to zero
secondfruitselected = fruitselected; secondfruitselpos = position;
if (firstfruitselected == secondfruitselected)
{
GeneralSoundManager.playSound(0, 1);// play happy sound - change code to GeneralSoundManager
//switch fruit image to blank and display blank at position clicked **
FruitToChooseFromImages.set (position, R.drawable.blank);
{ // remove viewable image / make blank
ImageView imageView = (ImageView) v;
imageView.setImageResource(R.drawable.blank);
}
int tempid = v.getId();
ImageView imgView = FruitToChooseFromImages.get(tempid);
imgView.setBackgroundResource(R.drawable.blank);
fruitleft = (fruitleft - 2);
}
else
{ // you selected the wrong fruit, sorry.
GeneralSoundManager.playSound(1, 1);
FruitToChooseFromImages.set (firstfruitselpos, firstfruitselected);
//
}
}
}
// end
if (fruitleft == 0)
{
//end game - add code here
}
}
});
}
// returns the sound to play depending on what image was clicked on
public int getrightsound(Integer position, Integer switchused) {
...etc....
return soundtoplay;
}
}
My gridview adapter code:
public class MyGridviewAdapter1 extends BaseAdapter
{
private ArrayList<Integer> FruitToChooseFromImages;
private Activity activity;
public MyGridviewAdapter1(Activity activity,ArrayList<Integer> FruitToChooseFromImages)
{
super();
this.FruitToChooseFromImages = FruitToChooseFromImages;
this.activity = activity;
}
public int getCount() {
return FruitToChooseFromImages.size();
}
public Integer getItem(int position) {
return FruitToChooseFromImages.get(position);
}
public long getItemId(int position) {
return 0;
}
public static class ViewHolder
{
public ImageView imgViewFlag;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.gridview_row, null);
view.imgViewFlag = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.imgViewFlag.setImageResource(FruitToChooseFromImages.get(position));
return convertView;
}
}
My Main xml code - gameonemenu:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_gravity="center"
android:background="#drawable/tree">
<GridView
android:id="#+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="4"
android:verticalSpacing="1dp"
android:horizontalSpacing="1dp"
android:stretchMode="columnWidth"
android:gravity="center" />
</LinearLayout>
My Grirdview_row xml code:
<ImageView
android:layout_height="64dp"
android:id="#+id/imageView1"
android:layout_width="64dp"
android:src="#drawable/blank"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
</RelativeLayout>
PS I used Grirdview_row xml which originally showed text but I don't need to display text only images but is this causing an issue?
PSS please keep your advice at the COMPLETE beginner level and include code if possible to match explanation. I cannot stress this enough. Thanks.

how to add gridview image to linearlayout in android

i want to add a images to grid view and then to linear layout.i tried below code
protected LinearLayout asLayout(final String message,final String path,boolean back){
LoaderImageView liv=new LoaderImageView(this,path);
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(100,120));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
(imageView).setPadding(10, 10, 10, 10);
liv.setBackgroundColor(0xFF000000);
linearWrapper = new GridView(mContext);
linearWrapper.addView(asLayout(fmsg,fpath,true));
linearWrapper.addView(asLayout(smsg,spath,false));
linerLayout.addView(linearWrapper);
the gridview was added but the images in grid view are not added .so please tell me the solution to how to add the gridview images to linearlayout.
Thanks in advance
Best Regards
You need an adapter for the grid view. Look at this to learn how to add adapters.
Edit 1: Sample code:
public class TestGrid extends Activity {
int[] myImages;
#Override public void OnCreate(Bundle icicle) {
super.onCreate(icicle);
GridView mGridView = new GridView(this);
/** Set up your data array with resource id's from your app. */
setAdapter(new TestAdapter());
setContentView(mGridView);
}
private class BenchAdapter extends BaseAdapter {
#Override public int getCount() { return (mContent != null) ? myImages.length : -1; }
#Override public Object getItem(int pos) { return pos; }
#Override public long getItemId(int pos) { return pos; }
#Override public View getView(int pos, View view, ViewGroup parent) {
if (myImages == null) return null;
GridView.LayoutParams lp = null;
if (getWidth() < getHeight()) lp = new GridView.LayoutParams(getWidth()/3, getHeight()/2);
else lp = new GridView.LayoutParams(getWidth()/2, getHeight()/3);
ImageView iv = new ImageView(TestGrid.this);
iv.setBackgroundResource(myImages[pos]);
iv.setLayoutParams(lp);
return iv;
}
}
Now what this will do is set a gridview as the activities content view. The Adapter will fill the content of the gridview. Without the adapter, the gridview would have no idea of what it should display.

Categories

Resources