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


49 comments:

  1. thank you so much ........... your post helped me a lot

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

    Android Training Institutes in Chennai

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

    ReplyDelete
  4. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.

    rpa training in marathahalli

    rpa training in btm

    rpa training in kalyan nagar

    rpa training in electronic city

    rpa training in chennai

    rpa training in pune

    rpa online training

    ReplyDelete
  5. Good Post, I am a big believer in posting comments on sites to let the blog writers know that they ve added something advantageous to the world wide web.
    python training in velachery
    python training institute in chennai

    ReplyDelete
  6. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    Devops Training in pune
    Devops Training in Chennai
    Devops training in sholinganallur
    Devops training in velachery

    ReplyDelete

  7. Howdy, would you mind letting me know which web host you’re utilizing? I’ve loaded your blog in 3 completely different web browsers, and I must say this blog loads a lot quicker than most. Can you suggest a good internet hosting provider at a reasonable price?
    Amazon Web Services Training in OMR , Chennai | Best AWS Training in OMR,Chennai
    Amazon Web Services Training in Tambaram, Chennai|Best AWS Training in Tambaram, Chennai

    ReplyDelete
  8. Hello! This is my first visit to When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several your blog!
    industrial safetyu courses in chennai

    ReplyDelete
  9. This list has several positive aspects. The users will find its features very convenient for their device. You can also find the support services http://puressay.com/blog/page/9 for your future publications.

    ReplyDelete
  10. Here this blog really give helpful information in Android App development. We have experienced app developers and well known for Best Android App Development services Nagpur.

    ReplyDelete
  11. This is quite educational arrange. It has famous breeding about what I rarity to vouch. Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved. This arrange is synchronous s informative impolite festivity to pity. I appreciated what you ok extremely here.

    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training


    ReplyDelete
  12. This post is really nice and pretty good maintained.
    Best R Training in Chennai

    ReplyDelete
  13. Excellent Blog. I really want to admire the quality of this post. I like the way of your presentation of ideas, views and valuable content. No doubt you are doing great work. I’ll be waiting for your next post. Thanks .Keep it up! Kindly visit us @
    Christmas Gift Boxes | Wallet Box
    Perfume Box Manufacturer | Candle Packaging Boxes | Luxury Leather Box | Luxury Clothes Box | Luxury Cosmetics Box
    Shoe Box Manufacturer | Luxury Watch Box

    ReplyDelete
  14. Wow, what an awesome spot to spend hours and hours! It's beautiful and I'm also surprised that you had it all to yourselves!
    Kindly visit us @ Best HIV Treatment in India | Top HIV Hospital in India | HIV AIDS Treatment in Mumbai | HIV Specialist in Bangalore
    HIV Positive Treatment in India | Medicine for AIDS in India

    ReplyDelete
  15. I am happy for sharing on this blog its awesome blog I really impressed. thanks for sharing. Great efforts.

    Get Best Service Now Training in Bangalore from Real Time Industry Experts with 100% Placement Assistance in MNC Companies. Book your Free Demo with Softgen Infotech.

    ReplyDelete
  16. Thank you for sharing such a nice post!

    Looking for Best Training Institute in Bangalore , India. Softgen Infotech is the best one to offers 85+ computer training courses including IT Software Course in Bangalore , India. Also, it provides placement assistance service in Bangalore for IT.

    ReplyDelete
  17. Its very Wonder full blog.I found some knowledge full information in the blog. thanks for sharing valuable. very nice… i really like your blog…CheapWays Digital Marketing Company in Nagpur

    ReplyDelete
  18. Astrum InfoTech Agency is the Best Digital Marketing Company in Delhi, They help to generate the profit and visitors traffic on website. If you are looking for grow the online visibility of your business then please contact us. We Offer Best Digital Marketing Service like SEO Service, SMO Service, PPC Service, Facebook Marketing Services, Email marketing service, graphic design services, website designing service and website development service etc. https://www.astruminfotech.com/

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. At the same time, to enjoy who eco-friendly brazilian hair, typically the daily news pouch needs to browse through an operation from build which may be through transaction with the help of eco values. keep it guys.
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  21. you give me a good example of learning android ,thanks a lot! https://tjproducts.com.sg/

    ReplyDelete
  22. Nice blog, it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing.
    DevOps Training in Chennai

    DevOps Course in Chennai

    ReplyDelete
  23. Great, thank you so much for sharing such an amazing blog with us. OGEN Infosystem is one of the best Website Designing, Website Development, SEO, PPC, and Digital Marketing Services in Delhi, India.
    Website Designing Company in India

    ReplyDelete
  24. Today I was surfing on the internet & found this article I read it & it is really amazing articles on the internet on this topic thanks for sharing such an amazing article.
    Web Designing Services in Nagpur

    ReplyDelete
  25. Are you looking for the best web design company in navi mumbai? If yes then connect with us to get an unique web design for your organization. Get all types of website design and development services by hiring CSS Founder.

    ReplyDelete
  26. We are a company CSS Founder that is known as the best Website designing company in Ghaziabad. Connect with if you want re-design or re-develop your existing website.

    ReplyDelete
  27. I read your article, it contains very nice information. Please keep posting like this so that i can read your blogs regularly.
    Upcoming projects in Sector 79 Noida

    ReplyDelete
  28. Forex Broker Canada Forex Broker USA Top List Of Forex Brokers By Country. Compare Forex Brokers, Forex Trading Platforms & Forex Indicators.

    ReplyDelete
  29. Amazing post, thank you for sharing this valuable and interesting post. Keep posting like this. Visit Al mumtaz tents in dubai and get the best tents for your party and events.
    Tent Companies in Dubai

    ReplyDelete
  30. Do you need smartphone insurance? If yes then connect with Assure India that provides best insurance services with a lot of features.

    ReplyDelete
  31. CSS Founder is known as the best website design & developement company across India. Connect with us if you want to take your business online. We can be the right choice for you.
    Website designing company in Delhi

    ReplyDelete
  32. Thank you so much for sharing this post, I appreciate your work. It was a great informative post
    Destination wedding in rishikesh

    ReplyDelete
  33. Very unique information I got here. so many blogs I search and I find but your blog is different blog then others great job you have done.
    Website design company in Kozhikode

    ReplyDelete
  34. Thanks for the informative and helpful post, obviously in your blog everything is good. Website design company in Tirupati

    ReplyDelete
  35. Thanks for the informative and helpful post, obviously in your blog everything is good. Website design company in Salem

    ReplyDelete
  36. I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very useful and knowledgeable. Digital Marketing Company in lucknow

    ReplyDelete
  37. IB Solar is a Tubular Battery provider in India. We provide the best quality solar batteries at the best price. Our company is one of the leading solar battery manufacturers in India
    What Our Client Says

    ReplyDelete
  38. I would recommend your website to everyone. You have a very good gloss. Write more high-quality articles. I support you..
    best-satellite-finders-in-india/
    best-sandals-with-arch-support-in-india/
    best-samovars-in-india/

    ReplyDelete
  39. TruePower is a trusted source for quality power products. We have been supplying the wholesale and retail market with our range of high-quality, affordable and reliable products since 2001. TruePower Solar Offgrid and Hybrid Inverter

    ReplyDelete
  40. If you are looking for a journal where you can connect with your peers, IJRAset is the right place. The journal has a very good reputation for publishing high-quality research papers. The journal also publishes research papers from various disciplines including engineering, chemistry, biology, and arts. Best Journal in India AIM

    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.