Android_800_thumb800

Build your own custom layouts and manage the related adapters for populating them with useful data.

Creating Custom Adapters

android_custom_adapter

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- This file is at /res/layout/gridviewcustom.xml -->
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dip"
    android:verticalSpacing="10dip"
    android:horizontalSpacing="10dip"
    android:numColumns="auto_fit"
    android:gravity="center"
    tools:context="com.trankyphat.app.customadapters.MainActivity">
</GridView>

gridimage.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/gridImageView"
        android:src="#555555"
    />

MainActivity.java

package com.trankyphat.app.customadapters;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.IntBuffer;

public class MainActivity extends AppCompatActivity {

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

        GridView gv = (GridView)findViewById(R.id.gridview);
        ModelAdapter adapter = new ModelAdapter(this);
        gv.setAdapter(adapter);
    }

    ///Fix OutOfMemory of Android
    //http://stackoverflow.com/questions/18583485/android-outofmemory-drawable
    //Load image to Right folder: xxxhdpi, hdpi,....
    public static Drawable getAssetImage(Context context, String filename) throws IOException {
        AssetManager assets = context.getResources().getAssets();
        InputStream buffer = new BufferedInputStream((assets.open("drawable/" + filename)));
        Bitmap bitmap = BitmapFactory.decodeStream(buffer);
        return new BitmapDrawable(context.getResources(), bitmap);
    }

    public static class ModelAdapter extends BaseAdapter {
        private static final String TAG = "ManateeAdapter";
        private static int convertViewCounter = 0;
        private Context mContext;
        private LayoutInflater mInflater;

        static class ViewHolder {
            ImageView image;
        }

        //If OutOfMemory Error. Load image to Right folder: xxxhdpi, hdpi,....
        private int[] models = {
                R.drawable.model1, R.drawable.model2, R.drawable.model3,
                R.drawable.model4, R.drawable.model5, R.drawable.model6, R.drawable.model7, R.drawable.model8,R.drawable.model9,R.drawable.model10,
                R.drawable.model11,R.drawable.model12,R.drawable.model13,R.drawable.model14,R.drawable.model15,R.drawable.model16,R.drawable.model17,R.drawable.model18
                ,R.drawable.model19};

        private Bitmap[] modelImages = new Bitmap[models.length];
        private Bitmap[] modelThumbs = new Bitmap[models.length];

        public ModelAdapter(Context context) {
            Log.v(TAG, "Constructing ManateeAdapter");
            this.mContext = context;
            mInflater = LayoutInflater.from(context);

            Bitmap bitmap;
            for (int i = 0; i < models.length; i++) {
                modelImages[i] = BitmapFactory.decodeResource(context.getResources(), models[i]);
                //Helful class form generating thumnbnail images from bitmap and videos ThumbnailUtils.
                modelThumbs[i] = Bitmap.createScaledBitmap(modelImages[i], 200, 200, false);
            }
        }

        @Override
        public int getCount() {
            Log.v(TAG, "in getCount()");
            return models.length;
        }

        /*
        *call the getViewTypeCount() method to determine how many different types
        of views could be displayed within the GridView

        For our purposes in this example, we
        set this to 1. However, if we had a ListView and wanted to put separators in between
        regular rows of data, we would have two types of views and would need to return 2 from
        getViewTypeCount().
        * */
        public int getViewTypeCount() {
            Log.v(TAG, "in getViewTypeCount()");
            return 1;
        }

        /*
        * getItemViewType() needs to return only an
        integer value to indicate which of our view types is at a particular position in the data.
        Therefore, if we had two types of views to return, getItemViewType() would need to return
        either 0 or 1 to indicate which type. If we have three types of views, this method needs to
        return 0, 1, or 2.
        * */
        public int getItemViewType(int position) {
            Log.v(TAG, "in getItemViewType() for position " + position);
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            Log.v(TAG, "in getView for position " + position +
                    ", convertView is " +
                    ((convertView == null) ? "null" : "being recycled"));
            //ConvertView not create
            if (convertView == null) {
                //inflate convert xml file to object store in memory for cache
                convertView = mInflater.inflate(R.layout.gridimage, null);
                convertViewCounter++;
                Log.v(TAG, convertViewCounter + " convertViews have been created");
                holder = new ViewHolder();
                holder.image = (ImageView) convertView.findViewById(R.id.gridImageView);

                convertView.setTag(holder);
            } else { //ConvertWill created, don't need inflate
                //Linking a ViewHolder to the View that we return
                //Get holder from cache
                holder = (ViewHolder) convertView.getTag();
            }
            holder.image.setImageBitmap(modelThumbs[position]);
            return convertView;
        }

        @Override
        public Object getItem(int position) {
            Log.v(TAG, "in getItem() for position " + position);
            return modelImages[position];
        }

        @Override
        public long getItemId(int position) {
            Log.v(TAG, "in getItemId() for position " + position);
            return position;
        }
    }
}

drawable source download: drawable-xxxhdpi

Other Controls

ScrollView is a control for setting up a View container with a vertical scrollbar. This is useful when you have too much to fit onto a single screen.
The ProgressBar and RatingBar controls are like sliders. The first shows the progress of some operation visually (perhaps a file download or music playing), and the second shows a rating scale of stars.
The Chronometer control is a timer that counts up. There’s a CountDownTimer class if you want something to help you display a countdown timer, but it’s not a View class. The Switch control, which functions like a ToggleButton but visually has a side-to-side presentation, was introduced in Android 4.0, along with the Space view, a lightweight view that can be used in layouts to more easily create spaces between other views.
WebView is a very special view for displaying HTML. It can do a lot more than that, including handling cookies and JavaScript and linking to Java code in your application. But before
you go implementing a web browser inside your application, you should carefully consider invoking the on-device web browser to let it do all that heavy lifting.

Apress Pro Android 5

Android 6 – More Advanced UI Layouts

Category: AndroidPrograming
0
2198 views

Join the discussion

Your email address will not be published. Required fields are marked *