Wednesday, February 13, 2013

b. How make a ListView in Android (That also supports Local language)

ListView is a nice way to display your text in a list. When the application is launched only the headings will be shown to the user and when the user click on a heading the List item will be shown below. If you want to display some text with main heading ListView provide a nice way to do it.

In this tutorial we will learn how to make a simple ListView which can also display your local Language Text. (Link to the source code is given at the end)

Here we require to make a main Java file an Adapter Java file, main xml file, a child xml file and a selector file.

Create a New Android Project by clicking as shown in the picture below

File>New>Android Application Project



 Give the application name as "CustomLanguageListView".

In the package name replace the "example" with "arise"

(TIP) Package name with example will not be accepted in Google Play.




Just click next to the next three child windows as nothing is to be changed.

In the Child Window named New Blank Activity give the activity name as "ListViewMainActivity". Layout name will be automatically changed.
Now click Finish to create the Project.

 
 Now your Project is created. Now you have to launch the main java file. For that click the following folders.

CustomLanguageListView > src > com.arise.customlanguagelistview > ListViewMainActivity.Java 

Now the main Java file is launched. add the following details to the file.
For easy understanding I have given the description as comments starting 
with "//"  
What we are doing is creating an ArrayList for the Headings and for List Items and adding each heading and List Items to the ArrayList. I am giving the first Heading as the current date, you can find the code for this below. Since I am going to display local Lnguage text, I have to save the font for the particular language in the "asset" folder, which will be explained later. You have to enter the headings and Items in your chosen language.

Initially  some errors will be shown, it will be disappeared when we create the support files.

package com.arise.customlanguagelistview;


import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.os.Bundle;
import android.app.ExpandableListActivity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;

public class ListViewMainActivity extends ExpandableListActivity implements
OnChildClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExpandableListView expandableLis= getExpandableListView();
        expandableLis.setDividerHeight(2);
        expandableLis.setGroupIndicator(null);
        expandableLis.setClickable(true);
       
        setGroupData();
        setChildGroupData();
       
        NewAdapter mNewAdapter = new NewAdapter(groupItem,childItem);       
        mNewAdapter.setInflater((LayoutInflater)       getSystemService(Context.LAYOUT_INFLATER_SERVICE),this);       
        getExpandableListView().setAdapter(mNewAdapter);       
        expandableLis.setOnChildClickListener(this);
           
    }
   
    public void setGroupData()// Setting headings of List View
    {
        final String currentDateString;//For displaying currentDate and Time in List View
        currentDateString = DateFormat.getDateInstance().format(new Date());//When you import Date Format use only import'Date Format' java.text
        groupItem.add("ഇന്നത്തെ തിയതി (Today is) - "+currentDateString);//For showing Todays Date along with your Custom Text
        groupItem.add("ഹെഡ്ഡിഗ് (Heading) 1");//Adding Heading 2 (You can add more by using add(heading name))
        groupItem.add("ഹെഡ്ഡിഗ്  (Heading) 2");//Adding heading 2
       
    }
    ArrayList<String> groupItem = new ArrayList<String>();//Setting Headings as Array List
    ArrayList<Object>childItem = new ArrayList<Object>(); //Setting List Items as Array List   
   
    public void setChildGroupData()//Adding list Items below the List Headings
    {
        //Adding List Items to The heading, Date
        ArrayList<String> child = new ArrayList<String>();
        child.add("ഒരു നല്ല ദിവസം ആശംസിക്കുന്നു. !(Greetings)");//Adding a Item called Greetings below the heading, Date
        childItem.add(child);
       
        //Adding List Items to 1st heading
        child = new ArrayList<String>();
        child.add ("ഐറ്റം (Item) 1"); //Adding Item 1 to the First heading
        child.add ("ഐറ്റം (Item) 2");//Adding Item 2 to the First heading
        childItem.add(child);
       
        //Adding List Items to 2nd heading
        child = new ArrayList<String>();
        child.add("ഐറ്റം (Item) 3");//Adding Item 1 to the 2nd heading
        child.add("ഐറ്റം (Item) 4");//Adding Item 2 to the 2nd heading
        childItem.add(child);   
       
       
    }
   
    @Override
    public boolean onChildClick (ExpandableListView parent, View v,
            int groupPosition, int childPosition, long id) {
        return true;
    }   

}

 

Now save the Java file and open the Main XML file from th folder shown below

CustomLanguageListView > res > layout >activity_list_view_main.xml

Now copy the following code in to the XML file,

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"   
    android:id="@+id/textView1"     
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_marginTop="40dp"
    android:layout_marginLeft="5dp" 
    android:drawableRight="@drawable/iconselector"   
    android:gravity="center_vertical"
    android:text="@string/hello_world"
    android:textColor="@color/orange"
    android:padding="10dp"
    android:textSelectHandleLeft="@string/hello_world"
    android:textSize="18sp"
    android:textStyle="bold" />


Initially  some errors will be shown, it will be disappeared when we create the support files.

Here we are creating a checked TextView for displaying the Headings of the ListView. 

Here it is given as "@drawable/iconselector" it is a link to the icon selector file. Which we will be creating later. which will be used for selecting some icons during expanding and collapsing as follows,

We will give a down arrow icon and an up arrow icon to the heading. When displayed normally the down arrow icon will be shown. so that user can understand that it is an expandable list and some text will be shown below when the down arrow is clicked.
When the list is fully expanded an up arrow picture is shown so that user can click it and collapse the list.

I have want to give  the text color orange to the Heading so a link to the color code in the string.xml file is given as "@color/orange"
we will modify the strings.xml file later.

Save and close the file.

Now we have to create an Adapeter for the ListView this is jest a  new Java file (known as class  file). To create this Right click on your package file named "com.arise.customlanguagelistview"  clcik "New" and then "Class" as shown in the picture.




 Now give it the name"NewAdapter" as shown in the diagram and click finish.



The new Java file will be automtically opened, Now enter the  following code in to the file.

The details are given as comments.

package com.arise.customlanguagelistview;

import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckedTextView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressWarnings("unchecked")
public class NewAdapter extends BaseExpandableListAdapter {
   
    public ArrayList<String> groupItem, tempChild;
    public ArrayList<Object> Childtem = new ArrayList<Object>();
    public LayoutInflater minflater;
    public Activity activity;
   

    public NewAdapter(ArrayList<String> grList, ArrayList<Object> childItem) {
        groupItem = grList;
        this.Childtem = childItem;
    }

    public void setInflater(LayoutInflater mInflater, Activity act) {
        this.minflater = mInflater;
        activity = act;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return null;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return 0;
    }
   
   
    @Override   
    public View getChildView(final int groupPosition, final int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {
        tempChild = (ArrayList<String>) Childtem.get(groupPosition);
        TextView text = null;
        if (convertView == null) {
            convertView = minflater.inflate(R.layout.child, null);
        }
        text = (TextView) convertView.findViewById(R.id.textView1);
        //To set a custom language font, first save the font file in asset folder.
        //You may create a folder named "fonts"inside asset folder and save the font file inside it
        //Now we have to set the Type face to the Text View as follows
        Typeface typeFace = Typeface.createFromAsset(convertView.getContext().getAssets(),"fonts/AnjaliOldLipi.ttf");
        text.setTypeface(typeFace);
       
              
        if (groupPosition==0 && childPosition== 0)//For setting a different color to the list Item 1 under Heading,Date
        //Please note that Group(Heading) Item and Child (list)Item starts with 0, instead of 1
        {
            ((TextView) text).setTextColor(Color.RED); //Giving Android default color red
            //instead of taking color value from string
        }
               
       
        else if (groupPosition==1 && childPosition== 1)//Use only "else if' for next item
        {
            ((TextView) text).setTextColor(Color.RED);
        }
         
       
       
        else //For setting a color to rest all item
        {
            ((TextView) text).setTextColor(convertView.getContext().getResources().getColor(R.color.steel_blue));
        }
       
       
        text.setText(tempChild.get(childPosition));
        convertView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(activity, tempChild.get(childPosition),
                        Toast.LENGTH_SHORT).show();
            }
        });
        return convertView;
    }
   
    @Override
    public int getChildrenCount(int groupPosition) {
        return ((ArrayList<String>) Childtem.get(groupPosition)).size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return null;
    }

    @Override
    public int getGroupCount() {
        return groupItem.size();
    }

    @Override
    public void onGroupCollapsed(int groupPosition) {
        super.onGroupCollapsed(groupPosition);
    }

    @Override
    public void onGroupExpanded(int groupPosition) {
        super.onGroupExpanded(groupPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return 0;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = minflater.inflate(R.layout.activity_list_view_main, null);
        }
        Typeface typeFace = Typeface.createFromAsset(convertView.getContext().getAssets(),"fonts/AnjaliOldLipi.ttf");
        ((CheckedTextView) convertView).setTypeface(typeFace);
       
         if (groupPosition==0 )
         //For setting a heading on the center and giving it a color
         {
             ((CheckedTextView) convertView).setTextColor(convertView.getContext().getResources().getColor(R.color.steel_blue));
             ((CheckedTextView) convertView).setGravity(Gravity.CENTER);
            }
          
            else
            // For Setting all other Headings on the Left and giving rest of all a different color
            {
                ((CheckedTextView) convertView).setTextColor(convertView.getContext().getResources().getColor(R.color.orange));
                ((CheckedTextView) convertView).setGravity(Gravity.LEFT);
            }
       
        ((CheckedTextView) convertView).setText(groupItem.get(groupPosition));
        ((CheckedTextView) convertView).setChecked(isExpanded);
        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

}


 In this file we assign the ArrayList headings and Items added in the Main Java file to the TextView.


 Since I am going to display the Local Language text (or custom Font) download the font for your language (Just search in Google for it) and copy the font in to the "assets" folder in your project as follows. For easy identification I created an inner folder named "fonts" inside the assets folder and saved the font file in to it.
I have used a malayalam font named "AnjaliOldLipi" see the picture below for details.






But if you want to display items in English the following codes are not required, it will work even though you do not delete it.

Typeface typeFace = Typeface.createFromAsset(convertView.getContext().getAssets(),"fonts/AnjaliOldLipi.ttf");
        ((CheckedTextView) convertView).setTypeface(typeFace);


 Now we have to create an XML file for the ListItems. 
Right Click on the layout file (CustomLanguageListView > res > layout >  ) and click "New" and "New Android XML File" as shown in the picture below.



Now give  name as "child" to the XML file as shown in the picture below, and click finish to create the file.




 Now copy the following code in to the new XML file,

<LinearLayout 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:background="@android:color/transparent" 
    android:clickable="true"
    android:orientation="vertical"
   
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical">
       
        <TextView
            android:id="@+id/textView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:gravity="center_vertical"
            android:layout_marginLeft="5dp"
            android:text="@string/hello_world"
            android:textColor="@color/steel_blue"
            android:textSize="15sp"
            android:textStyle="bold" />
    </LinearLayout>  

</LinearLayout>


Here we are creating a TextView inside a LinearLayout. The color of the text is given as blue, which is to be declared in the strings.XML file later.
Ignore the errors shown.

Now we have to create a selector file inside a new folder named "drawable"
for that Right click on the "res" folder and click "new" and click "folder"
as shown in the picture below.


Give the folder name as "drawable" and click "Finish" to create the folder, as shown in the picture below.

Right click on the newly created "drawable" folder and click "New" click "Android XML File" and Give the name "iconselector" to the file. Choose the root element as "selector" and click finish as shown in the picture below.


Now copy the following code in to the new file.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/up" android:state_checked="true"></item>
    <item android:drawable="@drawable/down"></item>
</selector>

Here we are specifying an icon named "up" from the drawable image folders, which is to be shown when the List is in expanded position and another icon named "down" when the List is in the collapsed position.

Save the file and close it.

Now we have to sepcify the color names in the strings.XML file.
Open file CustomLanguageListView > res > values > strings.xml

Copy the following code in to the file,

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">CustomLanguageListView</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <color name="steel_blue">#488AC7</color>
    <color name="orange">#F88017</color>   
   
</resources>


The color names and the corresponding color codes are given here. You can use html color codes in Android and give any name as you like. To get color code search "html color codes" in Google.

Lastly we have to save "up" and "down" arrow icons in to the drawable pictures folder. You can get the Android icons pack from the Google Developer site from the link here. Or you may choose any small icons as you want.

To choose an icon in an easy way open your Android manifest File
CustomLanguageListView > AndroidManifest.xml 
Now choose the application tab and click "browse" button next to the "icon"
This is actually intended to change the icon of the application but you can create an icon using this method.
see the image for details,


 In the next child window select "Create New Icon"



In the next child window select "Notification icon" and give the name as "up" and click next



In the next Child window Click image  and click "browse" and choose an icon.
If you have downloaded the font pack from google then choose 

All_icons > Holo dark > xhdpi > 1_navigation_collapse  

Click finish and cancel the Resource Chooser



Follow the same step above to create an "down" arrow icon
choose the following file

 All_icons > Holo dark > xhdpi >1_navigation_expand 

Click finish and cancel the Resource Chooser

 Lastly add the following lines (highligted in blue) to your Android manifest file for Holo Black theme, (see the picture below for details)

 <activity
            android:theme="@android:style/Theme"
            android:name="com.arise.customlanguagelistview.ListViewMainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" /> 



 

Now the project is ready to run.
When you run the project you will see the following result.


When you click on the heading the List Item is displayed as shown in the image shown below,






Now you have successfully completed a ListView Project.
You may download the source file from  This Link


5 comments:

  1. Nice post.Give it up. Thanks for share this article. For more visit:Web App Development

    ReplyDelete
  2. thank you so much ........... your post helped me a lot

    ReplyDelete
  3. Its really nice and informative blog..Thanks for sharing this blog..

    Android Training Institutes in Chennai

    ReplyDelete
  4. Nice blog, For more android tutorials, example, tips and tricks visit: http://www.viralandroid.com

    ReplyDelete
  5. Thanks for your article on Android technology. Android is an open source platform that allows developers to create stunning website loaded with various advanced features and functionalities. Android Training in Chennai | Android Course in Chennai

    ReplyDelete

Please give your valuable comments so as to know whether this blog is useful to you.You can also write helpful Android Development Syntax or Shortcuts or Tips.