Example usage for android.widget GridView setAdapter

List of usage examples for android.widget GridView setAdapter

Introduction

In this page you can find the example usage for android.widget GridView setAdapter.

Prototype

@Override
public void setAdapter(ListAdapter adapter) 

Source Link

Document

Sets the data behind this GridView.

Usage

From source file:com.maxleap.mall.fragments.MainFragment.java

private void initProductType(View view) {
    GridView gridView = (GridView) view.findViewById(R.id.grid_view);
    if (mProductTypes == null) {
        mProductTypes = new ArrayList<>();
    }//from  w w  w.  j ava  2s .  c o m
    if (mProductTypes.isEmpty()) {
        fetchProductTypeData();
    }
    mProductTypeAdapter = new ProductTypeAdapter(mContext, mProductTypes);
    gridView.setAdapter(mProductTypeAdapter);
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(mContext, ProductsActivity.class);
            intent.putExtra(ProductsActivity.INTENT_TITLE, mProductTypes.get(position).getTitle());
            intent.putExtra(ProductsActivity.INTENT_TYPE_ID, mProductTypes.get(position).getId());
            startActivity(intent);
        }
    });
}

From source file:biz.easymenu.easymenung.MenuPagerAdapter.java

private Object instantiateItemGrid(View pager, int position) {
    View v = li.inflate(R.layout.menupager, null);
    GridView listview = (GridView) v.findViewById(R.id.gridview);
    TextView tv = (TextView) v.findViewById(R.id.menuTitle);
    tv.setText(menuTitles.get(position).getLabel());

    ItemAdapter adapter = new ItemAdapter(context, position);
    ItemAdaptersList.add(position, adapter);
    listview.setAdapter(adapter);

    listview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            //Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
            FragmentManager fm = ((FragmentActivity) context).getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            DialogFragment f = new ItemFragment((DBRowItem) parent.getAdapter().getItem(position));
            Fragment prev = fm.findFragmentByTag("itemDialog");
            if (prev != null) {
                ft.remove(prev);//from ww w .j  av  a 2s.  c  om
                ft.commit();
            }
            f.show(ft, "itemDialog");
        }
    });
    ((ViewPager) pager).addView(v, 0);
    return v;
}

From source file:com.myinstagram.afinski.myinstgrmviewer.ui.ImageGridFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View v = inflater.inflate(R.layout.image_grid_fragment, container, false);
    final GridView mGridView = (GridView) v.findViewById(R.id.gridView);
    mGridView.setAdapter(mAdapter);
    mGridView.setOnItemClickListener(this);
    mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override//  ww  w  .  java2 s  .  c o m
        public void onScrollStateChanged(AbsListView absListView, int scrollState) {
            // Pause fetcher to ensure smoother scrolling when flinging
            if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
                // Before Honeycomb pause image loading on scroll to help with performance
                if (!Utils.hasHoneycomb()) {
                    mImageFetcher.setPauseWork(true);
                }
            } else {
                mImageFetcher.setPauseWork(false);
            }
        }

        @Override
        public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {
        }
    });

    // 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() {
        @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;
                    mAdapter.setNumColumns(numColumns);
                    mAdapter.setItemHeight(columnWidth);
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "onCreateView - numColumns set to " + numColumns);
                    }
                    if (Utils.hasJellyBean()) {
                        mGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        mGridView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                }
            }
        }
    });

    return v;
}

From source file:com.example.lowviscam.GalleryActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    if (isLight == true) {
        inflater.inflate(R.menu.gallery, menu);
    } else {/* ww w.  j a v a 2 s. com*/
        inflater.inflate(R.menu.gallery_dark, menu);
    }

    // Get the SearchView and set the searchable configuration
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    // Assumes current activity is the searchable activity
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
    searchView.setSubmitButtonEnabled(true);
    searchView.setOnQueryTextListener(new OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            search(query);
            // First image toast
            String firstResult;
            if (numSearchResults == 0) {
                firstResult = "No results found for  " + query + ".";
            } else {
                firstResult = "The first image result is titled " + tagList[0];
            }

            SpannableString s = new SpannableString(firstResult);
            s.setSpan(new TypefaceSpan(GalleryActivity.this, "APHont-Regular_q15c.otf"), 0, s.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            Toast.makeText(GalleryActivity.this, s, Toast.LENGTH_LONG).show();
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            if (TextUtils.isEmpty(newText)) {
                search("");
            }

            return true;
        }

        public void search(String query) {
            // hide keyboard
            InputMethodManager inputManager = (InputMethodManager) GalleryActivity.this
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(GalleryActivity.this.getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);

            // Fetch the {@link LayoutInflater} service so that new views can be created
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // Find the {@link GridView} that was already defined in the XML layout
            GridView gridView = (GridView) findViewById(R.id.grid);
            try {
                gridView.setAdapter(new CouponAdapter(inflater, createSearchedCoupons(query)));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    });

    return true;
    //return super.onCreateOptionsMenu(menu);
}

From source file:com.liu.Account.view.emojicon.EmojiconGridFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    GridView gridView = (GridView) view.findViewById(R.id.Emoji_GridView);
    Bundle bundle = getArguments();/*from   w  w w  . ja  v  a  2 s  .  c  o m*/
    if (bundle == null) {
        mData = People.DATA;
        mUseSystemDefault = false;
    } else {
        Parcelable[] parcels = bundle.getParcelableArray(EMOJICONS_KEY);
        mData = new Emojicon[parcels.length];
        for (int i = 0; i < parcels.length; i++) {
            mData[i] = (Emojicon) parcels[i];
        }
        mUseSystemDefault = bundle.getBoolean(USE_SYSTEM_DEFAULT_KEY);
    }
    gridView.setAdapter(new EmojiAdapter(view.getContext(), mData, mUseSystemDefault));
    gridView.setOnItemClickListener(this);
}

From source file:com.nike.plusgps.nikeplusgallery.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dbHelper = new DBHelper(this); // Creates the database
    dbHelper.deleteAllResponse(); // Clears the JSON response cache
    dbHelper.deleteAllMedia(); // Clears the JSON images cache

    // Get memory class of this device, exceeding this amount will throw an
    // OutOfMemory exception.
    final int memClass = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = 1024 * 1024 * memClass / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override//w w  w  .j a v  a2  s  .c o m
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in bytes rather than number of items.
            return bitmap.getByteCount();
        }
    };

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {

        setContentView(R.layout.activity_main_port);
        GridView view = (GridView) findViewById(R.id.gridView);
        flickrFeedList = new ArrayList<FlickrFeed>();
        new JSONParser()
                .execute("http://api.flickr.com/services/feeds/photos_public.gne?tags=nike&format=json");
        adapter = new FlickrFeedAdapter(getApplicationContext(), R.layout.single_elem_port, flickrFeedList,
                dbHelper, mMemoryCache);
        view.setAdapter(adapter);

    } else {

        setContentView(R.layout.activity_main_land);
        carouselElement = (LinearLayout) findViewById(R.id.carousel);
        // Compute width of a carousel item based on screen width and initial item count
        final DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        final int imageWidth = (int) (displayMetrics.widthPixels / INITIAL_ITEMS_COUNT);

        ImageView imageItem;
        String imgURL;
        for (int i = 0; i < flickrFeedList.size(); ++i) {
            imageItem = new ImageView(this);
            imgURL = flickrFeedList.get(i).getMedia();
            new DownloadImageTask(imageItem).execute(imgURL);
            imageItem.setLayoutParams(new LinearLayout.LayoutParams(imageWidth, imageWidth));
            carouselElement.addView(imageItem);
        }
    }
}

From source file:com.simplelife.seeds.android.utils.gridview.gridviewui.ImageGridFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View v = inflater.inflate(R.layout.activity_seeds_gridview_gridfragment, container, false);
    final GridView mGridView = (GridView) v.findViewById(R.id.gridView);
    mPullToRefreshView = (SeedsPullToRefreshView) v.findViewById(R.id.main_pull_refresh_view_grid);
    mGridView.setAdapter(mAdapter);
    mGridView.setOnItemClickListener(this);
    mPullToRefreshView.setOnHeaderRefreshListener(this);
    mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override/*w w w  .j ava  2 s  .c om*/
        public void onScrollStateChanged(AbsListView absListView, int scrollState) {
            // Pause fetcher to ensure smoother scrolling when flinging
            if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
                mImageFetcher.setPauseWork(true);
            } else {
                mImageFetcher.setPauseWork(false);
            }
        }

        @Override
        public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {
        }
    });

    // 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() {
        @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;
                    mAdapter.setNumColumns(numColumns);
                    mAdapter.setItemHeight(columnWidth);
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "onCreateView - numColumns set to " + numColumns);
                    }
                }
            }
        }
    });

    // Set a title for this page
    ActionBar tActionBar = getActivity().getActionBar();
    tActionBar.setTitle(R.string.seeds_details_top);

    // Show the details info of the seed
    // Prepare the seeds text info
    String tSeedName = Images.getSeedsEntity().getSeedName();
    String tSeedSize = Images.getSeedsEntity().getSeedSize();
    String tSeedFormat = Images.getSeedsEntity().getSeedFormat();
    String tSeedMosaic = (Images.getSeedsEntity().getSeedMosaic())
            ? getString(R.string.seeds_listperday_withmosaic)
            : getString(R.string.seeds_listperday_withoutmosaic);
    TextView tTextViewName = (TextView) v.findViewById(R.id.seed_grid_info_name);
    TextView tTextViewFormat = (TextView) v.findViewById(R.id.seed_grid_info_format);
    TextView tTextViewSize = (TextView) v.findViewById(R.id.seed_grid_info_size);
    TextView tTextViewMosaic = (TextView) v.findViewById(R.id.seed_grid_info_mosaic);

    if (null != tSeedName)
        tTextViewName.setText(getString(R.string.seedTitle) + ": " + tSeedName);
    if (null != tSeedFormat)
        tTextViewFormat.setText(getString(R.string.seedFormat) + ": " + tSeedFormat);
    if (null != tSeedSize)
        tTextViewSize.setText(getString(R.string.seedSize) + ": " + tSeedSize);
    if (null != tSeedMosaic)
        tTextViewMosaic.setText(getString(R.string.seeds_listperday_mosaic) + ": " + tSeedMosaic);

    return v;
}

From source file:com.sir_m2x.messenger.activities.ChatWindowPager.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat_window_pager);

    this.rootLayout = (RelativeLayout) findViewById(R.id.chatPagerParent);
    this.buzzAnimation = AnimationUtils.loadAnimation(this, R.anim.shake);

    this.mViewPager = (ViewPager) findViewById(R.id.chatPager);
    this.mAdapter = new ChatFragmentAdapter(getSupportFragmentManager());
    this.mViewPager.setAdapter(this.mAdapter);

    this.drawer = (SlidingDrawer) findViewById(R.id.drawer);
    this.btnClose = (Button) findViewById(R.id.btnClose);
    this.btnSmiley = (Button) findViewById(R.id.btnSmiley);
    GridView gv = (GridView) this.drawer.findViewById(R.id.content);
    gv.setAdapter(new SmileyAdapter());
    gv.setOnItemClickListener(new OnItemClickListener() {

        @Override//from www  . j a  v a 2  s .  c  o m
        public void onItemClick(final AdapterView<?> arg0, final View arg1, final int arg2, final long arg3) {
            String smiley = arg1.getTag().toString();
            Intent intent = new Intent();
            intent.setAction(MessengerService.INTENT_INSERT_SMILEY)
                    .putExtra(Utils.qualify("from"), ChatWindowPager.currentFriendId)
                    .putExtra(Utils.qualify("symbol"), smiley);

            sendBroadcast(intent);
            ChatWindowPager.this.drawer.animateClose();
        }
    });

    if (getIntent().hasExtra(Utils.qualify("friendId"))) {
        currentFriendId = getIntent().getExtras().getString(Utils.qualify("friendId"));
        if (!MessengerService.getFriendsInChat().keySet().contains(currentFriendId))
            MessengerService.getFriendIMs(this, currentFriendId);
    } else if (currentFriendId == "" || !MessengerService.getFriendsInChat().keySet().contains(currentFriendId))
        currentFriendId = MessengerService.getFriendsInChat().keySet().toArray()[0].toString();

    for (int i = 0; i < MessengerService.getFriendsInChat().size(); i++)
        if (MessengerService.getFriendsInChat().keySet().toArray()[i].toString().equals(currentFriendId)) {
            currentItem = i;
            break;
        }

    this.mTabPageIndicator = (TabPageIndicator) findViewById(R.id.chatIndicator);
    this.mTabPageIndicator.setViewPager(this.mViewPager, currentItem);
    this.mTabPageIndicator.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageScrollStateChanged(final int arg0) {
        }

        @Override
        public void onPageScrolled(final int arg0, final float arg1, final int arg2) {
        }

        @Override
        public void onPageSelected(final int arg0) {
            buzzWaitElapsed.set(true);
            ChatWindowPager.this.buzzAllower.cancel();
            ChatWindowPager.currentFriendId = ChatWindowPager.this.mAdapter.getId(arg0);
            currentItem = arg0;

            synchronized (MessengerService.getUnreadIMs()) {
                MessengerService.getUnreadIMs().remove(ChatWindowPager.this.mAdapter.getId(arg0));
                ChatWindowPager.this.mTabPageIndicator.notifyDataSetChanged();
            }
        }
    });

    this.btnClose.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(final View v) {
            Utils.saveConversationHistory(ChatWindowPager.this, currentFriendId);
            MessengerService.getFriendsInChat().remove(currentFriendId);
            currentItem--;
            if (currentItem < 0)
                if (MessengerService.getFriendsInChat().size() == 0) {
                    finish();
                    return;
                } else
                    currentItem++;

            currentFriendId = MessengerService.getFriendsInChat().keySet().toArray()[currentItem].toString();

            Intent intent = getIntent();
            overridePendingTransition(0, 0);
            intent.putExtra(Utils.qualify("friendId"), currentFriendId);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            finish();
            overridePendingTransition(0, 0);
            startActivity(intent);
        }
    });
    this.btnSmiley.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(final View v) {
            ChatWindowPager.this.drawer.animateOpen();
        }
    });

    MessengerService.getUnreadIMs().remove(currentFriendId);
    this.mViewPager.setCurrentItem(currentItem);
    this.mTabPageIndicator.notifyDataSetChanged();

    // reshow the default notification
    MessengerService.getNotificationHelper().showDefaultNotification(false, false);
}

From source file:com.seekon.yougouhui.activity.shop.RegisterShopActivity.java

private void initViews() {
    licenseInfoView = mInflater.inflate(R.layout.shop_register_license, null);
    baseInfoView = mInflater.inflate(R.layout.shop_register_base, null);
    pwdInfoView = mInflater.inflate(R.layout.shop_register_pwd, null);

    viewPager = (ViewPager) findViewById(R.id.shop_register_viewpager);
    viewPager.setOnPageChangeListener(this);
    viewPager.setCurrentItem(0);/*  www.  j  a  v  a 2  s.  c  o m*/

    List<View> pageViews = new ArrayList<View>();
    pageViews.add(licenseInfoView);
    pageViews.add(baseInfoView);
    pageViews.add(pwdInfoView);
    viewPager.setAdapter(new BasePagerAdapter(pageViews, pageTitles));

    GridView tradeView = (GridView) baseInfoView.findViewById(R.id.shop_trade_view);

    tradeAdapter = new TradeListAdapter(this, getTradeList());
    tradeView.setAdapter(tradeAdapter);

    loadTrades();

    nameView = (TextView) baseInfoView.findViewById(R.id.shop_name);
    addrView = (TextView) baseInfoView.findViewById(R.id.shop_address);
    descView = (TextView) baseInfoView.findViewById(R.id.shop_desc);
    shopImgView = (ImageView) baseInfoView.findViewById(R.id.shop_image);
    busiLicenseView = (ImageView) baseInfoView.findViewById(R.id.shop_busi_license);

    shopImgView.setLayoutParams(new FrameLayout.LayoutParams(SHOP_ICON_WIDTH, SHOP_ICON_WIDTH));
    shopImgView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, LOAD_IMAGE_REQUEST_CODE);
        }
    });

    busiLicenseView.setLayoutParams(new FrameLayout.LayoutParams(SHOP_ICON_WIDTH, SHOP_ICON_WIDTH));
    busiLicenseView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, LOAD_LICENSE_REQUEST_CODE);
        }
    });

    pwdView = (TextView) pwdInfoView.findViewById(R.id.password);
    pwdConfView = (TextView) pwdInfoView.findViewById(R.id.password_conf);
    userPhoneView = (TextView) pwdInfoView.findViewById(R.id.user_phone);
    userNameView = (TextView) pwdInfoView.findViewById(R.id.user_name);

    UserEntity user = RunEnv.getInstance().getUser();
    userPhoneView.setText(user.getPhone());
    ViewUtils.setEditTextReadOnly(userPhoneView);

    if (!UserUtils.isAnonymousUser()) {
        userNameView.setText(user.getName());
        ViewUtils.setEditTextReadOnly(userNameView);
    }
}

From source file:org.bwgz.quotation.fragment.SubjectFragment.java

private void updateQuotations(Cursor cursor) {
    Log.d(TAG, String.format("updateQuotations - cursor: %s (%d)", cursor, cursor.getCount()));

    if (cursor.getCount() != 0) {
        GridView gridView = viewHolder.quotation_grid;
        if (gridView.getAdapter() instanceof QuotationPicksCursorAdapter) {
            QuotationPicksCursorAdapter adapter = (QuotationPicksCursorAdapter) gridView.getAdapter();
            adapter.swapCursor(cursor);//from w w  w  .  j a va  2 s.  c  o  m
        } else {
            QuotationPicksCursorAdapter adapter = new QuotationPicksCursorAdapter(getView().getContext(),
                    cursor, R.layout.quotation_pick_view, getImageLoader());
            gridView.setAdapter(adapter);
        }
    }
}