Android_800_thumb800

List Controls with Adapter code examples

Clickable ListView

clickable_listview

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.trankyphat.app.listcontrols_listview.MainActivity">

    <!--ListView-->
    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView1"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

simple_list_row.xml

ListView Item layout

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="12dp"
    android:textSize="24sp" >
</TextView>

MainActivity.java

package com.trankyphat.app.listcontrols_listview;

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

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private ListView listView1;
    private ArrayAdapter<String> listAdapter1;

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

        listView1 = (ListView) findViewById(R.id.listView1);
        String[] someColors = new String[] { "Red", "Orange", "Yellow",
                "Green", "Blue", "Indigo", "Violet", "Black", "White"};
        ArrayList<String> colorArrayList = new ArrayList<String>();
        colorArrayList.addAll( Arrays.asList(someColors) );

        //Create an item of ListItem
        //Item get from simple_list_row.xml layout
        //Create list from Layout in simple_list_row
        listAdapter1 = new ArrayAdapter<String>(this, R.layout.simple_list_row,
                colorArrayList);

        //set Items to ListView
        listView1.setAdapter(listAdapter1);

        //Clickable Items in a ListView
        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            //getApplicationContext <=> this
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position
                    , long id) {
                Log.i("MyMessage", Integer.toString(position));
                String itemValue = (String) listView1.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(), itemValue,
                        Toast.LENGTH_LONG).show();
            }
        });
    }
}

Adding other controls with ListView

Get list item selected, add check icon in item

listitem_with_check

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.trankyphat.app.listcontrols_listview.MainActivity" >
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Submit selection" />
</LinearLayout>

simple_list_item_checked.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
/*
 * Copyright (C) 2006-2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
-->

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
    android:checkMark="?android:attr/textCheckMark"
    android:paddingLeft="6dip"
    android:paddingRight="6dip"
    />

MainActivity.java

package com.trankyphat.app.listcontrols_listview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private ListView listView1;
    private ArrayAdapter<String> listAdapter1;

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

        listView1 = (ListView) findViewById(R.id.listView1);
        String[] someColors = new String[] { "Red", "Orange", "Yellow",
                "Green", "Blue", "Indigo", "Violet", "Black", "White"};
        ArrayList<String> colorArrayList = new ArrayList<String>();
        colorArrayList.addAll( Arrays.asList(someColors) );

        //Create an item of ListItem
        //Item get from simple_list_row.xml layout
        //Create list from Layout in simple_list_row
        listAdapter1 = new ArrayAdapter<String>(this, R.layout.simple_list_item_checked,
                colorArrayList);

        //set Items to ListView
        listView1.setAdapter(listAdapter1);

        //Set multi choice on ListView
        listView1.setChoiceMode(listView1.CHOICE_MODE_MULTIPLE);

        //Clickable Items in a ListView
        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            //getApplicationContext <=> this
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position
                    , long id) {
                Log.i("MyMessage", Integer.toString(position));
                //Show value of item with Toast Notify
                String itemValue = (String) listView1.getItemAtPosition(position);
                Toast.makeText(getApplicationContext(), itemValue,
                        Toast.LENGTH_LONG).show();
            }
        });
    }

    //Do submit selection button click
    public void doClick(View view) {
        int count=listView1.getCount();

        //Get all item checked
        SparseBooleanArray viewItems = listView1.getCheckedItemPositions();

        //Log all item checked
        for(int i=0; i<count; i++) {
            if(viewItems.get(i)) {
                String selectedColor = (String) listView1.getItemAtPosition(i);
                Log.v("ListViewDemo", selectedColor + " is checked at position " + i);
            }
        }
    }
    //Another way to get selected item
    public void doClick2(View view) {
            if(!listAdapter1.hasStableIds()) {
                Log.v("MyMessage", "Data is not stable");
                return;
            }
            long[] viewItems = listView1.getCheckedItemIds();
            for(int i=0; i<viewItems.length; i++) {
                String selectedColor = (String) listView1.getItemAtPosition(i);
                Log.v("ListViewDemo", selectedColor + " is checked at position " + i);
            }
        }
    }
}

GridView Control

Most widget toolkits offer one or more grid-based controls. Android has a GridView control that can display data in the form of a grid. Note that although we use the term data here, the contents of the grid can be text, images, and so on.

android_control_gridview

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.trankyphat.app.listcontrols_gridview.MainActivity">

    <GridView
        android:id="@+id/gridView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dp"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:numColumns="auto_fit"
        android:columnWidth="100dp"
        android:stretchMode="columnWidth"
        android:gravity="center" />
</RelativeLayout>

MainActivity.java

package com.trankyphat.app.listcontrols_gridview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private GridView gridView1;
    private ArrayAdapter<String> listAdapter1;

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

        gridView1 = (GridView) findViewById(R.id.gridView1);
        String[] someColors = new String[] { "Red", "Orange", "Yellow",
                "Green", "Blue", "Indigo", "Violet", "Black", "White"};
        ArrayList<String> colorArrayList = new ArrayList<String>();
        colorArrayList.addAll(Arrays.asList(someColors));

        //Using simple list item layout of android
        listAdapter1 = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, colorArrayList);
        gridView1.setAdapter( listAdapter1 );
    }
}

Spinner Control

The Spinner control is like a drop-down menu. It is typically used to select from a relatively short list of choices. If the choice list is too long for the display, a scrollbar is automatically added for you.

listcontrol_spinner

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.trankyphat.app.listcontrols_spinner.MainActivity">

    <Spinner
        android:id="@+id/spinner" android:prompt="@string/spinnerprompt"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RelativeLayout>

MainActivity.java

package com.trankyphat.app.listcontrols_spinner;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends AppCompatActivity {

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

        String[] planets = new String[] { "Earth", "Mars", "Jupiter",
                "Saturn", "Uranus", "Neptune"};

        Spinner spinner = (Spinner)findViewById(R.id.spinner);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, planets);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

    }
}

Gallery Control

comming soon…

Android 6 – List Controls

Category: AndroidPrograming
0
2839 views

Join the discussion

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