Wednesday, September 7, 2016

Android ListView Attributes. (fastScrollEnabled)





1. Attributes of the Android ListView.

Attributes Description
divider Drawable or color to draw between list items.
dividerHeight Height of the divider.
entries Reference to an array resource that will populate the ListView.
footerDividersEnabled When set to false, the ListView will not draw the divider before each footer view.
headerDividersEnabled When set to false, the ListView will not draw the divider after each header view.
cacheColorHint Indicates that this list will always be drawn on top of solid, single-color opaque background.
choiceMode Defines the choice behavior for the view.
drawSelectorOnTop When set to true, the selector will be drawn over the selected item.
fastScrollEnabled Enables the fast scroll thumb that can be dragged to quickly scroll through the list.
listSelector Drawable used to indicate the currently selected item in the list.
scrollingCache When set to true, the list uses a drawing cache during scrolling.
smoothScrollbar When set to true, the list will use a more refined calculation method based on the pixels height of the items visible on screen.
stackFromBottom Used by ListView and GridView to stack their content from the bottom.
textFilterEnabled When set to true, the list will filter results as the user types.
transcriptMode Sets the transcript mode for the list.

2. Enabling the fast scroll thumb. (fastScrollEnabled)

The scroll function is activated since several items have been added to the ListView, you can use it by moving up or down while pressing and holding your finger. By the way, if a very large amount of items are in the ListView, There is a discomfort to have to take action to move several times to move to the last item on the first item.

In this case, you can make quick positioning by enabling "fastScrollEnabled" attribute and moving the thumb.

  * android:fastScrollEnabled - Enabling the fast scroll thumb.
        > true or false.

If you do not use "fastScrollEnabled" or set it to "false", the thumb is not appeared.

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

ListView Attrribute fastScrollEnabled false

If "fastScrollEnabled" is set to "true", you can see the thumb and make quick positioning by touch.

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fastScrollEnabled="true" />

ListView Attribute fastScrollEnabled true

3. References.

.END.

Android ListView Attributes (entries)



1. Attributes of the Android ListView.

Attributes Description
divider Drawable or color to draw between list items.
dividerHeight Height of the divider.
entries Reference to an array resource that will populate the ListView.
footerDividersEnabled When set to false, the ListView will not draw the divider before each footer view.
headerDividersEnabled When set to false, the ListView will not draw the divider after each header view.
cacheColorHint Indicates that this list will always be drawn on top of solid, single-color opaque background.
choiceMode Defines the choice behavior for the view.
drawSelectorOnTop When set to true, the selector will be drawn over the selected item.
fastScrollEnabled Enables the fast scroll thumb that can be dragged to quickly scroll through the list.
listSelector Drawable used to indicate the currently selected item in the list.
scrollingCache When set to true, the list uses a drawing cache during scrolling.
smoothScrollbar When set to true, the list will use a more refined calculation method based on the pixels height of the items visible on screen.
stackFromBottom Used by ListView and GridView to stack their content from the bottom.
textFilterEnabled When set to true, the list will filter results as the user types.
transcriptMode Sets the transcript mode for the list.


2. Loading a ListView items from an Array Resource. (entries)

When we made the example adding items to the ListView in [Android ListView. (How to use an Android ListView.)], we wrote java codes that use an Adapter. But there is a way to add items directly from a resource instead of using the Adapter.
It is just to use "entries" attribute.
  * android:entries - Load items from an array resource.
        > Simpler way than using Adapter in a java code.
        > Useful to static contents, such as the menu.
The use of "entries" attribute is simple.
First, create a resource XML file that contains "<string-array>" into "/res/values" and set the name of the array resource to the ListView's "entries" attribute.
An example of using "entries" is shown below.

2.1 Create a resource XML file that contains the string array into "/res/values"

In this example, I create the resource XML file in the name of "my_array.xml".
And "myarray" is the name of the string array.
[STEP-1 for "entries"] "my_array.xml" - Create "/res/values/my_array.xml"
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="myarray">
        <item>LIST1</item>
        <item>LIST2</item>
        <item>LIST3</item>
    </string-array>
</resources>

2.2 Set the name of the array resource to the ListView's "entries" attribute.

[STEP-2 for "entries"] "activity_main.xml" - setting "entries".
    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:entries="@array/myarray" />
It's done.

2.3 Screenshot

You can see the same result as we wrote in [Android ListView. (How to use an Android ListView.)].
ListView Attributes entries

3. References.


.END.

Tuesday, September 6, 2016

Android ListView Attributes (divider, dividerHeight)




1. Attributes of the Android ListView.

Attributes Description
divider Drawable or color to draw between list items.
dividerHeight Height of the divider.
entries Reference to an array resource that will populate the ListView.
footerDividersEnabled When set to false, the ListView will not draw the divider before each footer view.
headerDividersEnabled When set to false, the ListView will not draw the divider after each header view.
cacheColorHint Indicates that this list will always be drawn on top of solid, single-color opaque background.
choiceMode Defines the choice behavior for the view.
drawSelectorOnTop When set to true, the selector will be drawn over the selected item.
fastScrollEnabled Enables the fast scroll thumb that can be dragged to quickly scroll through the list.
listSelector Drawable used to indicate the currently selected item in the list.
scrollingCache When set to true, the list uses a drawing cache during scrolling.
smoothScrollbar When set to true, the list will use a more refined calculation method based on the pixels height of the items visible on screen.
stackFromBottom Used by ListView and GridView to stack their content from the bottom.
textFilterEnabled When set to true, the list will filter results as the user types.
transcriptMode Sets the transcript mode for the list.

2. Drawing the divider between ListView items. (divider, dividerHeight)

Usually, when multiple items are added to the ListView, the divider with gray color is drawn between items. By the way, What should I do if I want to change the divider's style(color, height or image) ?
It is to use "divider" attribute.
  * android:divider - Drawable or color to draw between list items.
        > Color (#rgb, #argb, #rrggbb, "#aarrggbb")
        > Drawable (@drawable/xxx)
        > Another resource (?android:attr/yyy)
Also, the divider's height can be adjusted by using "dividerHeight" attribute.
  * android:dividerHeight - set height of the divider.
        > Dimension (sp, px, dp, in, mm)
Examples of "divider" and "dividerHeight" are shown below.

2.1 Default Divider. ("divider" attribute is not used)

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
ListView Default Divider



2.2 Color Divider. (Green and 2dp height)

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="#00FF00"
        android:dividerHeight="2dp" />
ListView Color Divider

2.3 Drawable Divider.

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@drawable/dotted_divider" />
ListView Drawable Divider

2.4 Transparent Divider. (Set alpha to "0x00")

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="#00000000" />
ListView Transparent Divider

3. References.

.END.

Thursday, September 1, 2016

Android Custom ListView with a Button. (How to add a Button to an Android Custom ListView.)



1. Android ListView with Button

Many types of widgets are used in an Android Custom ListView. I introduced the Custom ListView having an ImageView and TextViews at [Android Custom ListView. (How to customize an Android ListView.)].
In this article, I'll explain that how to add button to an Android Custom ListView.

2. Adding a Button to the ListView

The item of the ListView is organized as follows.
ListView item's layout

2.1 Workflow

Workflow for the Custom ListView with a Button

2.2 Add a ListView to the Activity.

Declare "<ListView>" to "content_main.xml"(or "activity_main.xml") that is layout resource XML file of MainActivity.
[STEP-1] "content_main.xml" - Declare "<ListView>"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.madwin.listviewbuttonexample.MainActivity"
    tools:showIn="@layout/activity_main">

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

2.3 Configure the ListView item's layout.

Add the item's layout XML file. The file name is "listview_btn_item.xml".
[STEP-2] "/res/layout/listview_btn_item.xml" - Configure ListView item's layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/imageView1"
        android:layout_weight="1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text=""
        android:id="@+id/textView1"
        android:textSize="16dp"
        android:textColor="#000000"
        android:gravity="center_vertical"
        android:layout_weight="4" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="Select No"
        android:layout_weight="1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="Execute Toast"
        android:layout_weight="1" />

</LinearLayout>

2.4 Define class for the ListView item.

Do you remember that you define class for the Custom ListView item at [Android Custom ListView. (How to customize an Android ListView.)]? Define class in the same way.
[STEP-3] "ListViewBtnItem.java" - Define class for ListView item.
import android.graphics.drawable.Drawable;

public class ListViewBtnItem {
    private Drawable iconDrawable ;
    private String textStr ;

    public void setIcon(Drawable icon) {
        iconDrawable = icon ;
    }
    public void setText(String text) {
        textStr = text ;
    }

    public Drawable getIcon() {
        return this.iconDrawable ;
    }
    public String getText() {
        return this.textStr ;
    }
}

2.5 Implement the custom adapter.

In this example, I use an ArrayAdapter instead of a BaseAdapter.
[STEP-4] "ListViewBtnAdapter.java" - Implement the custom adapter.
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

public class ListViewBtnAdapter extends ArrayAdapter implements View.OnClickListener  {
    // define a listener interface for Button click event.
    public interface ListBtnClickListener {
        void onListBtnClick(int position) ;
    }

    // save the resource id from the constructor.
    int resourceId ;
    // save ListBtnClickListener from the constructor.
    private ListBtnClickListener listBtnClickListener ;


    // the constructor of ListViewBtnAdapter
    ListViewBtnAdapter(Context context, int resource, ArrayList<ListViewBtnItem> list, ListBtnClickListener clickListener) {
        super(context, resource, list) ;

        // copy resource id.
        this.resourceId = resource ;

        this.listBtnClickListener = clickListener ;
    }

    // return the view for the item.
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final int pos = position ;
        final Context context = parent.getContext();

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(this.resourceId/*R.layout.listview_btn_item*/, parent, false);
        }

        // get the view widget's reference.
        final ImageView iconImageView = (ImageView) convertView.findViewById(R.id.imageView1);
        final TextView textTextView = (TextView) convertView.findViewById(R.id.textView1);

        // get the item data.
        final ListViewBtnItem listViewItem = (ListViewBtnItem) getItem(position);

        // update view by the item data.
        iconImageView.setImageDrawable(listViewItem.getIcon());
        textTextView.setText(listViewItem.getText());

        // process button1 click event.
        Button button1 = (Button) convertView.findViewById(R.id.button1);
        button1.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                textTextView.setText(Integer.toString(pos + 1) + " item is selected.");
            }
        });

        // save the position to button2's tag and set this adapter as the click event listener.
        Button button2 = (Button) convertView.findViewById(R.id.button2);
        button2.setTag(position);
        button2.setOnClickListener(this);

        return convertView;
    }

    // process button2 click event.
    public void onClick(View v) {
        if (this.listBtnClickListener != null) {
            this.listBtnClickListener.onListBtnClick((int)v.getTag()) ;
        }
    }

}


2.6 Add the function for loading sample data.

Add the function for loading sample data.
[STEP-5] "MainActivity.java" - load data.
    public boolean loadItemsFromDB(ArrayList<ListViewBtnItem> list) {
        ListViewBtnItem item ;
        int i ;

        if (list == null) {
            list = new ArrayList<ListViewBtnItem>() ;
        }

        i = 1 ;

        // create items.
        item = new ListViewBtnItem() ;
        item.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_account_box_black_36dp)) ;
        item.setText(Integer.toString(i) + " item.") ;
        list.add(item) ;
        i++ ;

        item = new ListViewBtnItem() ;
        item.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_account_circle_black_36dp)) ;
        item.setText(Integer.toString(i) + " item.") ;
        list.add(item) ;
        i++ ;

        item = new ListViewBtnItem() ;
        item.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_language_black_36dp)) ;
        item.setText(Integer.toString(i) + " item.") ;
        list.add(item) ;
        i++ ;

        item = new ListViewBtnItem() ;
        item.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_lightbulb_outline_black_36dp)) ;
        item.setText(Integer.toString(i) + " item.") ;
        list.add(item) ;

        return true ;
    }

2.7 Create the Adapter and set it to the ListView.

Create the Adapter and set it to the ListView.
[STEP-6] "MainActivity.java" - Create the Adapter and set it to the ListView in onCreate().
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ListView listview ;
        ListViewBtnAdapter adapter;
        ArrayList<ListViewBtnItem> items = new ArrayList<ListViewBtnItem>() ;

        // load items.
        loadItemsFromDB(items) ;

        // create the adapter.
        adapter = new ListViewBtnAdapter(this, R.layout.listview_btn_item, items, this) ;

        // set the adapter to the ListView.
        listview = (ListView) findViewById(R.id.listview1);
        listview.setAdapter(adapter);
    }

2.8 Process Button's click event.

Below codes were already wrote in previous steps.
But I'll write them once more for showing that how to process the button's click event.
"[STEP-7.1]" shows that how to process the button's simple click event.
[STEP-7.1] "ListViewBtnAdapter.java" - process button1 click event
    // process button1 click event.
    Button button1 = (Button) convertView.findViewById(R.id.button1);
    button1.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            textTextView.setText(Integer.toString(pos + 1) + " item is selected.");
        }
    });
"[STEP-7.2] ~ [STEP-7.5]" shows that how to transfer the ListView item's click event to MainActivity.
[STEP-7.2] "ListViewBtnAdapter.java" - define a listener interface for Button click event.
public class ListViewBtnAdapter extends ArrayAdapter implements View.OnClickListener  {
    // define a listener interface for Button click event.
    public interface ListBtnClickListener {
        void onListBtnClick(int position) ;
    }

    // save ListBtnClickListener from the constructor.
    private ListBtnClickListener listBtnClickListener ;

    // ...
}
[STEP-7.3] "ListViewBtnAdapter.java" - add the listener to constructor's parameter.
public class ListViewBtnAdapter extends ArrayAdapter implements View.OnClickListener  {

    // ...

    ListViewBtnAdapter(Context context, int resource, ArrayList<ListViewBtnItem> list, ListBtnClickListener clickListener) {
        super(context, resource, list) ;

        // copy resource id.
        this.resourceId = resource ;

        this.listBtnClickListener = clickListener ;
    }

    // ...
}
[STEP-7.4] "ListViewBtnAdapter.java" - call onListBtnClick() of ListBtnClickListener.
    // process button2 click event.
    public void onClick(View v) {
        // call onListBtnClick() of ListBtnClickListener.
        if (this.listBtnClickListener != null) {
            this.listBtnClickListener.onListBtnClick((int)v.getTag()) ;
        }
    }
[STEP-7.5] "MainActivity.java" - extends ListViewBtnAdapter.ListBtnClickListener.
public class MainActivity extends AppCompatActivity implements ListViewBtnAdapter.ListBtnClickListener {

    // ...

    @Override
    public void onListBtnClick(int position) {
        Toast.makeText(this, Integer.toString(position+1) + " item is selected.", Toast.LENGTH_SHORT).show() ;
    }
}

2.9 Build and run.

Build and run "app".

3. Screenshot.

Screenshot1 of the Custom ListView with a Button

Screenshot2 of the Custom ListView with a Button

4. References.

.END.

Thursday, August 25, 2016

Android Custom ListView. (How to customize an Android ListView.)



1. Android Custom ListView.

In the previous article [Android ListView. (How to use an Android ListView)], I explained that what ListView is and how to use it. But the ListView that I explained consists of a TextView widget only.
In general, a ListView is more complex having ImageView, Button or another view widgets than just a TextView is used only. This types of ListView is called "Custom ListView".
Now, I'm going to explain how to make an Android Custom ListView.

2 How to customize an Android ListView.

The item of ListView is organized as follows.
item's layout of the Custom ListView

2.1 Workflow

Worlflow for the Custom ListView Example.

2.2 Add ListView to Activity.

Declare "<ListView>" to "activity_main.xml"(or "content_main.xml") that is layout resource XML file of MainActivity.
[STEP-1] "activity_main.xml" - Declare "<ListView>"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.recipes4dev.customlistviewexample.MainActivity"
    tools:showIn="@layout/activity_main">

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

2.3 Configure ListView item's layout.

I didn't make item's layout in the previous article [Android ListView. (How to use Android ListView)] since the item had a TextView only. For the item with only a TextView, "simple_list_item_1" is sufficient to use. ("simple_list_item_1" is a built-in XML layout that is defined in the Android SDK. It has only one TextView and can be refered as "android.R.layout.simple_list_item_1" in your java codes.)
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, LIST_MENU) ;
Adapter and simple_list_item_1

However, for the Custom ListView, item's layout has to be added and configured.
So, I'll add ListView item's layout XML as "/res/layout/listview_item.xml" and write as follows.
[STEP-2] "/res/layout/listview_item.xml" - Configure ListView item's layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/imageView1"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="4">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/textView1"
            android:textSize="24dp"
            android:textColor="#000000"
            android:gravity="center_vertical"
            android:layout_weight="2" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/textView2"
            android:textSize="16dp"
            android:textColor="#666666"
            android:layout_weight="1" />
    </LinearLayout>

</LinearLayout>

2.4 Define class for ListView item.

Define class having 2 String and 1 Drawable for ListView item data.
[STEP-3] "ListViewItem.java" - Define class for ListView item.
import android.graphics.drawable.Drawable;

public class ListViewItem {
    private Drawable iconDrawable ;
    private String titleStr ;
    private String descStr ;

    public void setIcon(Drawable icon) {
        iconDrawable = icon ;
    }
    public void setTitle(String title) {
        titleStr = title ;
    }
    public void setDesc(String desc) {
        descStr = desc ;
    }

    public Drawable getIcon() {
        return this.iconDrawable ;
    }
    public String getTitle() {
        return this.titleStr ;
    }
    public String getDesc() {
        return this.descStr ;
    }
}

2.5 Implement custom adapter.

You wrote a layout resource XML for ListView item's view.
You defined a class for ListView item's data.
Now, what you have to do is to implement custom adapter by extending "BaseAdapter".
[STEP-4] "ListViewAdapter.java" - Implement custom adapter.
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class ListViewAdapter extends BaseAdapter {
    // ArrayList for saving user data.
    private ArrayList<ListViewItem> listViewItemList = new ArrayList<ListViewItem>() ;

    public ListViewAdapter() {

    }

    // mandatory : return item count in the data set.
    @Override
    public int getCount() {
        return listViewItemList.size() ;
    }

    // mandatory : return item view that displays the data.
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final int pos = position;
        final Context context = parent.getContext();

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.listview_item, parent, false);
        }

        ImageView iconImageView = (ImageView) convertView.findViewById(R.id.imageView1) ;
        TextView titleTextView = (TextView) convertView.findViewById(R.id.textView1) ;
        TextView descTextView = (TextView) convertView.findViewById(R.id.textView2) ;

        ListViewItem listViewItem = listViewItemList.get(position);

        iconImageView.setImageDrawable(listViewItem.getIcon());
        titleTextView.setText(listViewItem.getTitle());
        descTextView.setText(listViewItem.getDesc());

        return convertView;
    }

    // mandatory : return the row id associated with the specified position.
    @Override
    public long getItemId(int position) {
        return position ;
    }

    // mandatory : return the data item associated with the specified position.
    @Override
    public Object getItem(int position) {
        return listViewItemList.get(position) ;
    }

    // convenient : add the data for a item to list.
    public void addItem(Drawable icon, String title, String desc) {
        ListViewItem item = new ListViewItem();

        item.setIcon(icon);
        item.setTitle(title);
        item.setDesc(desc);

        listViewItemList.add(item);
    }
}

2.6 add image files(png, jpg) to project.

Copy image files to the project. ("/res/drawable")
Copy image files to project.

Image files can be refered as "R.drawable.XXX" in a java code. (ex, "R.drawable.ic_account_box_black_36dp")

2.7 Create an adapter and set it to ListView.

Finally, you have to create an adapter and set it to the ListView.
[STEP-5] "MainActivity.java" - Create a adapter and set it to ListView.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView listview ;
        ListViewAdapter adapter;

        // create adapter
        adapter = new ListViewAdapter() ;

        // get listview handle.
        listview = (ListView) findViewById(R.id.listview1);
        listview.setAdapter(adapter);

        // add the 1st item.
        adapter.addItem(ContextCompat.getDrawable(this, R.drawable.ic_account_box_black_36dp),
                "Box", "Account Box Black 36dp") ;
        // add the 2nd item.
        adapter.addItem(ContextCompat.getDrawable(this, R.drawable.ic_account_circle_black_36dp),
                "Circle", "Account Circle Black 36dp") ;
        // add the 3rd item.
        adapter.addItem(ContextCompat.getDrawable(this, R.drawable.ic_assignment_ind_black_36dp),
                "Ind", "Assignment Ind Black 36dp") ;
    }

2.8 Handle the click event.

Handle the click event if you need.
[STEP-6] "MainActivity.java" - Handle a click event.
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // create OnItemClickListener and set it to ListView.
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                // get item
                ListViewItem item = (ListViewItem) parent.getItemAtPosition(position) ;

                String titleStr = item.getTitle() ;
                String descStr = item.getDesc() ;
                Drawable iconDrawable = item.getIcon() ;

                // TODO : use item data.
            }
        }) ;
    }

2.9 Build and run.

Build and run "app".

3. Android Custom ListView Screenshot 

Android Custom ListView Screenshot

4. References.

.END.

Wednesday, August 17, 2016

Android ListView. (How to use an Android ListView.)





1. Android ListView

ListView is a view group that displays a list of scrollable items. ListView items are listed in a vertical direction.
ListView and ViewGroup
the ListView is one of the components used most frequently in constituting Android UI (User Interface). And Contacts and Preferences of the Android system are prime example of the ListView.
ListView Example

1.1 Adapter

An Adapter acts as a bridge between an ListView and the underlying data for that view.
Adapter's role.

2. How to use an Android ListView.

Now, let's make the example that can see how to use an Android ListView.

2.1 Workflow

Workflow for an Android ListView example.

2.2 Add ListView to Activity.

The first thing to do when you use ListView is to add ListView to Activity. In this example, MainActivity will be the owner of ListView. Declare "<ListView>" to "activity_main.xml"(or "content_main.xml") that is layout resource XML file of MainActivity.
[STEP-1] "activity_main.xml" - Declare "<ListView>"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.recipes4dev.example.listviewexample1.MainActivity"
    tools:showIn="@layout/activity_main">

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

2.3 Declare the user data.

the ListView of the example will show the text by using a TextView widget. So, I declare an array of String type.
[STEP-2] "MainActivity.java" - Declare array of String type.
public class MainActivity extends AppCompatActivity {
    static final String[] LIST_MENU = {"LIST1", "LIST2", "LIST3"} ;

    // ... continued.
}

2.4 Create an Adapter and set it to the ListView.

Now that your data is ready, you have to create an adapter and set it to the ListView. There are several kinds of Adapter in Android SDK. You can choose to use for your application. Here, ArrayAdapter are used because String array are declared as an input. (But BaseAdapter is normally used.)
[STEP-3] "MainActivity.java" - Create Adapter and set it to ListView in onCreate().
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState) ;
        setContentView(R.layout.activity_main) ;

        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, LIST_MENU) ;

        ListView listview = (ListView) findViewById(R.id.listview1) ;
        listview.setAdapter(adapter) ;

        // ... continued.
    }

2.5 Handle the click event for ListView items.

Usually the ListView is simply used to display the data as a list form, but it may be used clickable menu item by handling the click event for ListView items. You can set the click event listener for handling the event and have to override onItemClick() method.
[STEP-4] "MainActivity.java" - Handle click event for ListView items.
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView parent, View v, int position, long id) {

            // get TextView's Text.
            String strText = (String) parent.getItemAtPosition(position) ;

            // TODO : use strText
        }
    }) ;
onItemClick()'s Parameters are,
  • parent : The ListView where the click happened.
  • view : The view within the ListView that was clicked
  • position : The position of the view in the adapter.
  • id : The row id of the item that was clicked.
If "LIST2" item is clicked,
  • parent : listview
  • view : TextView's object within listview.
  • position : 1
  • id : 1

2.6 Build and run.

Finally, Build and run "app".

3. Android ListView Basic Example Screenshot.

you can see the following screen. it was captured at Nexus 7 2nd(2013) version.
ListView Example Screenshot

4. References

.END.