Android Basic Course: Selection Widgets

    Android provides a flexible framework for defining choices on the widgets. Specifically, Android provides a framework of data adapters, provides a common interface for the selections list, from static arrays to database content. Selection views-widgets represent a list of choices, is managed by an adapter to supply the actual choice.
    Through this post, I will talk about some popular widgets: Spinner, AutoCompleteTextView, ListView with check box and GridView.

Drop-down list (Spinner)

    Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one.
   Like the ListView, you must provide a data coordination and the rows displaying based on the methods setAdapter(), and hook a listener object for selection item through setOnItemSelectedListener().  If you want to change the display of the drop-down list, you need to reconfigure the adapter (not the Spinner widget). Using methods setDropDownViewResource() to provide the resource ID to view.
   For example, declaring a Spinner instance in xml layout like this:
   In Java file, set Spinner adapter and handle item selected event like describe above:
package info.devexchanges.slectionwidgetandroid;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class SpinnerActivity extends AppCompatActivity {

    private Spinner spinner;
    private ArrayAdapter<String> spinnerAdapter;
    private TextView selectedText;

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

        spinner = (Spinner)findViewById(R.id.spinner);
        selectedText = (TextView)findViewById(R.id.select_text);

        String[] alphabetArray = Utils.readTextFromAssets(this, "vi_alphabet.txt");

        if (alphabetArray != null) {
            spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, alphabetArray);
            spinner.setAdapter(spinnerAdapter);
        }
        spinner.setOnItemSelectedListener(onItemSelected());
    }

    private AdapterView.OnItemSelectedListener onItemSelected() {
        return new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView adapterView, View view, int i, long l) {
                selectedText.setText((String)adapterView.getSelectedItem());
            }

            @Override
            public void onNothingSelected(AdapterView adapterView) {

            }
        };
    }
}
    This screen when running app:
    Note: in this example, I generated dummy data from an text file in assets resource. So, please put your text file in src/main/assets folder first:
    And this is code for reading it and set data (Strings) to a static array:
package info.devexchanges.slectionwidgetandroid;

import android.app.Activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Utils {

    public static String[] readTextFromAssets(Activity activity, String fileName) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader(activity.getAssets().open(fileName)));

            // do reading, usually loop until end of file reading
            String mLine;
            String[] splited = null;
            while ((mLine = reader.readLine()) != null) {
                splited = mLine.split("\\s+");
            }
            return splited;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
    You can set Spinner data by another simple way, and how to access resources/files in Android I would mention in the next posts.

GridView

    Like other platform, GridView is a view that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter. Like ListView, it's also a subclass of AbsListView, but it has some it's own attributes:
  • android:num_of_columns: usually, set "auto_fit" to this property, number of columns will be auto-fixed with device width.
  • android:verticalSpacing and android:horizontalSpacing: Indicates how much space should exist between the items in the grid.
  • android:columnWidth: Indicates how many pixels per column should be.
  • android:stretchMode: Figure out what happens to any available space that is not occupied by a column or space between the items. It may be columnWidth, that column will occupy spots available space, or spacingWidth, spaces between the columns will occupy more space.
    On the other hand, the GridView works like any other widget selection, which is used setAdapter() to provide the data, called setOnItemSelectedListener() to register the listener selection,... Consider the following example:
package info.devexchanges.slectionwidgetandroid;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;

public class GridViewActivity extends AppCompatActivity {

    private GridView gridView;
    private ArrayAdapter<String> adapter;

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

        gridView = (GridView) findViewById(R.id.gridview);

        String[] alphabetArray = Utils.readTextFromAssets(this, "vi_alphabet.txt");

        if (alphabetArray != null) {
            adapter = new ArrayAdapter<>(this, R.layout.item_gridview, R.id.text_view, alphabetArray);
            gridView.setAdapter(adapter);
        }

        gridView.setOnItemClickListener(onItemClickListener());
    }

    private AdapterView.OnItemClickListener onItemClickListener() {
        return new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String selectedLetter = adapterView.getAdapter().getItem(i).toString();
                Toast.makeText(GridViewActivity.this, selectedLetter, Toast.LENGTH_SHORT).show();
            }
        };
    }
}
    Output:

AutoCompleteTextView

    AutoCompleteTextView is kind of a cross between EditText (field) and Spinner. With autocomplete feature, when users type, the text will be treated as a prefix filter, compare text is entered as a prefix with a list of candidates. The result of this will show up in a list of choices, drop down from the filed (as with Spinner). Users can type in the full path (for example, something not in the list), or select an item from the list to make the field values.
    You can provide an adapter for AutoCompleteTextView, which containing lists of candidates worth through setAdapter(). However, because users can type in something that's not in the list, should not support selection AutoCompleteTextView listeners. Instead, you may register a TextWatcher, to know when documents change. These events will occur by manual typing or from a selection from the dropdown list.
    Create a xml layout file include a AutoCompleteTextView object first:
    In programmatically code, apart from familiar works above, we add a TextWatcher for AutoCompleteTextView to get it's changing text to a TextView. Full code for this Activity:
package info.devexchanges.slectionwidgetandroid;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

public class AutoCompleteActivity extends AppCompatActivity {

    private AutoCompleteTextView autoCompleteTextView;
    private TextView selectedText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_autocomplete_textview);
        autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete_textview);
        selectedText = (TextView)findViewById(R.id.text_result);

        String[] alphabetArray = Utils.readTextFromAssets(this, "lorem_ipsum_text.txt");
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, alphabetArray);
        autoCompleteTextView.setAdapter(adapter);

        autoCompleteTextView.addTextChangedListener(onTextWatcher());
    }

    private TextWatcher onTextWatcher() {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                selectedText.setText(autoCompleteTextView.getText().toString());
            }
        };
    }
}
    We final have this screen:

ListView with CheckBox

    Android Default SDK also provide the checkable list through integrating ListView and CheckBox (each row has it's own CheckBox ones). To make this trick, you must declare the choice mode through ListView attribute android:choiceMode in layout file:
    Change choice mode value to "multipleChoice", your ListView will be multi-checkable.
    In programmatically code, we can use the default layouts for each ListView row when creating it's adapter:
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, itemsListView);
listView.setAdapter(adapter);
    And we'll have a ListView which user can check only a row:
    Change the layout params when create Adapter to android.R.layout.simple_list_item_multiple_choice, we have this output:
    Note: I haven't clearly presented this default way to make a checkable list because it has many limitations. I recommended customizing it by yourself. By this, you can checkout my previous posts:

Conclusions

    Over here, I've presented the selection widgets in Android. This demo project (include all part above) now available on @Github, you can download by click the button below.  If you think that I have presented here sketchy, please review the project carefully.
    References to official docs:



Share


Previous post
« Prev Post
Next post
Next Post »