By Alvin Alexander. Last updated: August 3, 2019
Before I completely delete this code from my current Android application, I want to make a copy of it here. It was intended to show a series of quotes (text phrases) in a “Grid” (GridView
), but (a) I never got it working as desired, and (b) I decided I didn’t want it in my application anyway.
Here’s the source code for the Java controller/fragment class:
package com.alvinalexander.foo; import java.util.ArrayList; import android.app.Fragment; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; public class QuotesGridFragment extends Fragment { GridView gridView; ArrayList<String> mItems; ThumbnailDownloader<ImageView> mThumbnailThread; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); new FetchItemsTask().execute(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_quotes_grid, container, false); gridView = (GridView)v.findViewById(R.id.quotesGridView); setupAdapter(); return v; } void setupAdapter() { if (getActivity() == null || gridView == null) return; if (mItems != null) { gridView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_gallery_item, mItems)); } else { gridView.setAdapter(null); } } private class FetchItemsTask extends AsyncTask<Void,Void,ArrayList<String>> { @Override protected ArrayList<String> doInBackground(Void... params) { ArrayList<String> quotes = DatabaseManager.get(getActivity()).getAllActiveQuotes(); return quotes; } @Override protected void onPostExecute(ArrayList<String> items) { mItems = items; setupAdapter(); } } }
And here’s the code for the fragment’s layout file:
<GridView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/quotesGridView" android:layout_width="match_parent" android:layout_height="wrap_content" android:columnWidth="120dp" android:numColumns="auto_fit" android:stretchMode="columnWidth" android:clickable="true" android:fadeScrollbars="true"> </GridView>
As I noted above, the GridView
didn’t look very good (yet), but at least this is some starter code in case you want to create a grid/wall of text quotes (or if I decide later that I want to try this feature again).