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:net.potterpcs.recipebook.TagSearchDialog.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.tagsearch, container, false);
    RecipeBook app = (RecipeBook) getActivity().getApplication();
    Cursor cursor = app.getData().getAllTags();
    GridView grid = (GridView) v.findViewById(R.id.tagsearchgrid);

    clicked = null;/*from w  w  w  .  j a  va 2s. c  o m*/

    adapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1, cursor,
            new String[] { RecipeData.TT_TAG }, new int[] { android.R.id.text1 }, 0);

    grid.setAdapter(adapter);
    grid.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            RecipeBookActivity activity = (RecipeBookActivity) getActivity();
            Intent intent = new Intent(activity, RecipeBookActivity.class);
            if (activity.isSearchMode()) {
                intent.putExtra(RecipeBook.SEARCH_EXTRA, activity.getSearchQuery());
            }
            if (activity.isTimeSearch()) {
                intent.putExtra(RecipeBook.TIME_EXTRA, true);
                intent.putExtra(RecipeBook.TIME_EXTRA_MIN, activity.getMinTime());
                intent.putExtra(RecipeBook.TIME_EXTRA_MAX, activity.getMaxTime());
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            adapter.getCursor().moveToPosition(position);
            intent.putExtra(RecipeBook.TAG_EXTRA,
                    adapter.getCursor().getString(adapter.getCursor().getColumnIndex(RecipeData.TT_TAG)));
            startActivity(intent);
            dismiss();
        }
    });

    return v;
}

From source file:ti.org.dmfs.android.colorpicker.PaletteFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    /*/*from w  w  w .  j a  v a2s.  c  o  m*/
     * TODO: build the layout programmatically to get rid of the resources,
     * so we can distribute this in a single jar
     */
    final ViewGroup rootView = (ViewGroup) inflater
            .inflate(RHelper.getLayout("org_dmfs_colorpickerdialog_palette_grid"), container, false);
    final GridView gridview = (GridView) rootView.findViewById(android.R.id.content);

    mAdapter = new PaletteGridAdapter(getActivity(), mPalette);
    gridview.setAdapter(mAdapter);
    gridview.setOnItemClickListener(this);
    gridview.setNumColumns(mAdapter.getNumColumns());

    /*
     * Adjust the layout of the gridview to a square.
     * 
     * Inspired by Bill Lahti, see
     * http://blahti.wordpress.com/2012/07/23/three
     * -variations-of-image-squares/
     */
    gridview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @SuppressLint("NewApi")
        public void onGlobalLayout() {
            int parentHeight = rootView.getHeight() - rootView.getPaddingTop() - rootView.getPaddingBottom();
            int parentWidth = rootView.getWidth() - rootView.getPaddingLeft() - rootView.getPaddingRight();

            int gridWidth = Math.min(parentWidth, parentHeight);

            int columnSpacing;
            if (android.os.Build.VERSION.SDK_INT >= 16) {
                columnSpacing = gridview.getHorizontalSpacing() * (mAdapter.getNumColumns() - 1);
            } else {
                /*
                 * TODO: getHorizontalSpacing() has been introduced
                 * in SDK level 16. We need to find a way to get get
                 * the actual spacing. Until then we use a hard
                 * coded value of 8 dip.
                 * 
                 * One way would be to use a dimension in the
                 * layout. That would allow us to resolve the
                 * dimension here. However, that would be one step
                 * away from a library without resource
                 * dependencies. Maybe there is an Android dimension
                 * resource with a reasonable value?
                 */
                DisplayMetrics metrics = inflater.getContext().getResources().getDisplayMetrics();
                if (android.os.Build.VERSION.SDK_INT > 10) {
                    columnSpacing = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, metrics)
                            * (mAdapter.getNumColumns() - 1);
                } else {
                    // Android 2 seems to add spacing around the
                    // entire gridview
                    columnSpacing = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, metrics)
                            * mAdapter.getNumColumns();
                }
            }

            // width of a single column
            int columnWidth = (gridWidth - columnSpacing) / mAdapter.getNumColumns();

            // estimated width of the grid
            int actualGridWidth = mAdapter.getNumColumns() * columnWidth + columnSpacing;

            // add padding to center the grid if we don't use the
            // entire space due to rounding errors
            if (actualGridWidth < gridWidth - 1) {
                int padding = (gridWidth - actualGridWidth) / 2;
                if (padding > 0) {
                    gridview.setPadding(padding, padding, padding, padding);

                }
            } else {
                // no padding needed
                gridview.setPadding(0, 0, 0, 0);
            }

            // set the column width
            gridview.setColumnWidth(columnWidth);

            android.view.ViewGroup.LayoutParams params = gridview.getLayoutParams();
            if (params == null || params.height != gridWidth) // avoid
            // unnecessary
            // updates
            {
                LayoutParams lparams = new LinearLayout.LayoutParams(gridWidth, gridWidth);
                gridview.setLayoutParams(lparams);
            }
        }
    });
    return rootView;
}

From source file:net.FarmTab.app.InventoryActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.icons_grid);

    mPreferences = getPreferences(MODE_PRIVATE);

    /* TODO: for demo only */
    Preferences.storePrefs(mPreferences.edit(), "1", "OldMacDonald", true);

    mItems = fetchInventory();//from   w  w w . j a  v  a 2 s .co m

    GridView grid = (GridView) findViewById(R.id.itemsGrid);
    GridAdapter mAdapter = new GridAdapter();
    grid.setAdapter(mAdapter);

    grid.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            InventoryItem item = new InventoryItem("pumpkin", true);

            popupDialog(item);
        }
    });

}

From source file:models.newArrivalFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_newarrival, container, false);
    getActivity().setTitle("New Arrivals!");

    //animation when enter home page
    rootView.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.image_click));

    //download the URL's asynchronously (put the info in the teaInfo object)
    try {/*from   w  w w .ja va2 s  .  c om*/
        teaInfo = new GetTeaInfoTask().execute(new ApiConnector()).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    //make the gridview and set its adapter
    GridView gridView = (GridView) rootView.findViewById(R.id.grid_view_new_arrival);
    GridViewCustomAdapter gvAdapter = new GridViewCustomAdapter(getActivity(), teaInfo.imageURLs,
            teaInfo.teaNames);
    gridView.setAdapter(gvAdapter);

    //onclick listener for gridview
    gridView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

            Bundle teaViewArgs = new Bundle();
            teaViewArgs.putString("teaName", teaInfo.teaNames.get(position));
            teaViewArgs.putString("teaImgUrl", teaInfo.imageURLs.get(position));
            teaViewArgs.putString("teaDesc", teaInfo.teaDescriptions.get(position));
            Fragment newFragment = new TeaViewFragment();
            newFragment.setArguments(teaViewArgs);

            if (newFragment != null) {
                flipCard(newFragment);
            }
        }

        private void flipCard(Fragment newFragment) {
            mShowingBack = true;
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .setCustomAnimations(R.anim.card_flip_right_in, R.anim.card_flip_right_out,
                            R.anim.card_flip_left_in, R.anim.card_flip_left_out)
                    .replace(R.id.frame_container, newFragment).addToBackStack(null).commit(); // create new fragment and allow user to go back to previous fragment          
        }

    });

    return rootView;
}

From source file:com.battlelancer.seriesguide.ui.ListsFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mAdapter = new ListItemAdapter(getActivity(), null, 0);

    // setup grid view
    GridView list = (GridView) getView().findViewById(android.R.id.list);
    list.setAdapter(mAdapter);
    list.setOnItemClickListener(this);
    list.setEmptyView(getView().findViewById(android.R.id.empty));
    list.setFastScrollAlwaysVisible(false);
    list.setFastScrollEnabled(true);/*from w  w w .ja  v a  2 s.  c  om*/

    getLoaderManager().initLoader(LOADER_ID, getArguments(), this);
}

From source file:com.ces.cloudnote.app.bitmapfun.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//  www .j av  a  2 s .com
        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);
                    }
                }
            }
        }
    });

    return v;
}

From source file:com.example.android.justforus.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set activity_main.xml to be the layout for this activity
    setContentView(R.layout.activity_main);

    // 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);

    // Initialize the adapter with all the coupons. Set the adapter on the {@link GridView}.
    gridView.setAdapter(new CouponAdapter(inflater, createAllCoupons()));

    // Set a click listener for each coupon in the grid
    gridView.setOnItemClickListener(this);
}

From source file:com.replicaappforyou.app.MainActivity.java

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

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

    //TODO: create grid layout
    //Find the {@link GridView} that was already defined in the XML layout
    GridView gridView = (GridView) findViewById(R.id.grid);

    //Initialize the adapter with all the coupons setting the adapter on the {@link GridView}
    gridView.setAdapter(new CouponAdapter(inflater, createAllCoupons()));

    //Set a click listener for each coupon in the grid
    gridView.setOnItemClickListener(this);
}

From source file:com.vbehl.connections.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() {
        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);
            }//  w  ww  .java 2 s. co m
        }

        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() {
        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) {
                        LogUtils.d(TAG, "onCreateView - numColumns set to " + numColumns);
                    }
                }
            }
        }
    });

    return v;
}

From source file:com.bilibili.socialize.share.utils.selector.BaseSharePlatformSelector.java

protected static GridView createShareGridView(final Context context,
        AdapterView.OnItemClickListener onItemClickListener) {
    GridView grid = new GridView(context);
    ListAdapter adapter = new ArrayAdapter<ShareTarget>(context, 0, shareTargets) {
        // no need scroll
        @Override/* w w  w.j  a  v  a  2s  .  c  o m*/
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.bili_socialize_shareboard_item, parent, false);
            view.setBackgroundDrawable(null);
            ImageView image = (ImageView) view.findViewById(R.id.bili_socialize_shareboard_image);
            TextView platform = (TextView) view.findViewById(R.id.bili_socialize_shareboard_pltform_name);

            ShareTarget target = getItem(position);
            image.setImageResource(target.iconId);
            platform.setText(target.titleId);
            return view;
        }
    };
    grid.setNumColumns(-1);
    grid.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
    grid.setColumnWidth(context.getResources().getDimensionPixelSize(R.dimen.bili_socialize_shareboard_size));
    grid.setLayoutParams(new ViewGroup.LayoutParams(-1, -2));
    grid.setSelector(R.drawable.bili_socialize_selector_item_background);
    grid.setAdapter(adapter);
    grid.setOnItemClickListener(onItemClickListener);
    return grid;
}