Monday, 30 July 2012

Localization

Android supports a wide range of languages.
If you want to know all the supported languages you can visit here .

Using localization concept one can display a text in a any language corresponding to his Locale.
Suppose a client(may be a person from France) is interested in getting his app design in English when he is in a country where the locale is English and  in his country he would be looking to see his app in French. In this situation we can use Localization.

Consider the following screen shots :






The first snapshot is HELLO WORLD in French.
When ever we change the Locale to France we can see the HELLO WORLD in French language.

For this to happen we must do the following :



  • Create a folder under the res folder with name  values-fr. Here 'fr' refers to French language.
  • Create a strings.xml file similar to the one in the values folder. 
  • If we need to display a TextView in different languages in different Locales, set the text of the textview using the strings folder.
        Consider the following : 
         
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.         android:layout_width="fill_parent"
  3.         android:layout_height="fill_parent" >

  4.         <TextView
  5.             android:id="@+id/main_TV_text"
  6.             android:layout_width="wrap_content"
  7.             android:layout_height="wrap_content"
  8.             android:layout_alignParentLeft="true"
  9.             android:layout_alignParentTop="true"
  10.             android:layout_marginLeft="38dp"
  11.             android:layout_marginTop="29dp"
  12.             android:text="@string/text"
  13.             

  14.     </RelativeLayout>



If u consider the 13-th line : Here i am setting the text to the TextView using a value in strings.xml file like below : 
  
       <string name="text">HELLO WORLD</string>



  • Now in the strings.xml file of values-fr folder write HELLO WORLD in french (use Google translator ) 

        <string name="text">BONJOUR TOUT LE MONDE</string>


Whenever the Locale changes the appropriate values folder will be used.


Testing it in emulator :
                Go to settings --> Language & keyboard --> Select Language -->  and select Français(France).

Later  when you run your application again you can see  BONJOUR TOUT LE MONDE displayed on the screen.

We can also use .ttf files which i will discuss in the next post.

Any suggestions are welcomed.
Please comment if anyone has some or the other problem with this one.












































Friday, 27 July 2012

Alert Box (code)


Now lets discuss a small topic which may be used sometimes.
An Alert Box......................

Sometimes we may come across few alert boxes saying Do you want to continue with a single button or two or three buttons.

Alert box, as the name suggests it alerts and interrupts the user to perform short tasks that are related to the application.

When alert box is displayed the current task loses focus and the dialog accepts the whole focus.
This simply means that we can interact only with the alert box and not with the previous task.


Now lets get into the details how to display an alert dialog box in android.

An Alert box can be done either through java code or inflating an xml file
While we are inflating an xml file we can have any views other than buttons in the alert box. (This is a custom alert box).

  • 1.A simple way to create an alert dialog is to set the theme property for the activity which you want to display as a alert dialog.

          android:theme="@android:style/Theme.Dialog"


  • Now lets discuss how it can be done using java code.


Firstly do the following :

 1. AlertDialog.Builder builder = new AlertDialog.Builder(YourClassName.this);

       Here we are creating a Builder object for the current context. This will be used in the following                             steps.





If you observe we can see the following : 

  1. Title to the alert dialog box (ALERT)
  2. Message in the Alert dialog Box (this is a alert box.Click yes/no)
  3. And finally two buttons yes and no.
As i said the Builder object is used in the following steps, the title , message and the buttons are set using the builder object.

To set the title to the dialog box, we can use the following line line : 
                   builder.setTitle("ALERT");

To set a message to the alert dialog box, we use
                   builder.setMessage("this is an alert box. Click Yes/No");

And the 'yes' and 'no' buttons can be displayed and can be handled using the code :
  1. buillder.setPositiveButton("yes", new DialogInterface.OnClickListener() {

  2. @Override
  3. public void onClick(DialogInterface dialog, int which) {

  4. Toast.makeText(DisplayAlert.this, "You clicked yes",
  5. Toast.LENGTH_SHORT).show();
  6. }
  7. });
  8.   

And the other button for 'no' can be dislayed and handled using a similar code as above.

  1. builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

  2. @Override
  3. public void onClick(DialogInterface dialog, int which) {

  4. Toast.makeText(DisplayAlert.this, "You clicked no",
  5. Toast.LENGTH_SHORT).show();
  6. dialog.dismiss();
  7. }
  8. });
In the similar way we can define a neutral button.


Finally we need to create and show the alert box which can be done using the following lines :
  1. AlertDialog alertdialog = builder.create();

  2. alertdialog.show();

Now let us see a sample example where i am having a button and the click of the button an alert dialog box appears.

Following is the xml file :
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="fill_parent"
  4.     android:layout_height="fill_parent"
  5.     android:orientation="vertical" >

  6.     <Button
  7.         android:id="@+id/main_BTN_display"
  8.         android:layout_width="wrap_content"
  9.         android:layout_height="wrap_content"
  10.         android:text="DISPLAY" />

  11. </LinearLayout>
And following is the activity file :


  1. import android.app.Activity;
  2. import android.app.AlertDialog;
  3. import android.content.DialogInterface;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. import android.widget.Toast;

  9. /**
  10.  * 
  11.  * 
  12.  * Class that displays an alert dialog box and handles Yes/No buttons.
  13.  */
  14. public class DisplayAlert extends Activity implements OnClickListener {
  15. Button mBTN_display;

  16. @Override
  17. public void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.main);
  20. mBTN_display = (Button) findViewById(R.id.main_BTN_display);
  21. mBTN_display.setOnClickListener(this);
  22. }

  23. @Override
  24. public void onClick(View arg0) {

  25. display_Alert();
  26. }

  27. /**
  28.  * This method displays an alert dialog box and handles Yes/No buttons
  29.  */
  30. private void display_Alert() {

  31. AlertDialog.Builder builder = new AlertDialog.Builder(DisplayAlert.this);
  32. builder.setTitle("ALERT");
  33. builder.setMessage("this is an alert box. Click Yes/No");


    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    builder.setView(input);

  34. builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {

  35. @Override
  36. public void onClick(DialogInterface dialog, int which) {

  37. Toast.makeText(DisplayAlert.this, "You clicked yes",
  38. Toast.LENGTH_SHORT).show();
  39. }
  40. });
  41. builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

  42. @Override
  43. public void onClick(DialogInterface dialog, int which) {

  44. Toast.makeText(DisplayAlert.this, "You clicked no",
  45. Toast.LENGTH_SHORT).show();
  46. dialog.dismiss();
  47. }
  48. });

  49. AlertDialog alertdialog = builder.create();
  50. alertdialog.show();

  51. }
  52. }
The text in the box is used to place an edit text in the alert box. (simply a customized alert box).
There is no change in the manifest file.
Thus on running the application we can get a alert dialog on click of the button.

Any suggestions are welcomed.
Please comment if anyone has some or the other problem with this one.




















































Thursday, 19 July 2012

Custom List View

Some Times we may come across few situations where we need to display an image and information about the image beside it.
consider the following image as an example : 


This task can be accomplished in many ways and am gonna discuss a way using Base Adapter.


In general a list view will contain only a single textview in each row  which will be inflated (by default) for the number of items. But if we need another view other than a textview or an additional view we need to use an alternative.


This inflation is done by using an additional xml file which will be inflated onto the list view.
consider an xml file with a list view as below :


main.xml



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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
   
  <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    
     <ListView
        android:id="@+id/main_LV_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
</LinearLayout>

And we are going to inflate the following xml file so that we can get an image and a textview in each row .
row.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >


    <ImageView
        android:id="@+id/row_IV_android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />


    <TextView
        android:id="@+id/row_TV_detail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />


</LinearLayout>


Now let us consider how to use the BaseAdapter class
we need to use a class which extends the baseAdapter class.
After extending the baseadapter class we need to add the 4 unimplemented methods of baseAdapter.


Consider the following code : 
  1. class CustomAdapter extends BaseAdapter {
  2. Context cont;

  3. public CustomAdapter(Context c) {
  4. // TODO Auto-generated constructor stub
  5. cont = c;
  6. }

  7. @Override
  8. public int getCount() {
  9. // TODO Auto-generated method stub
  10. return 5;
  11. }

  12. @Override
  13. public Object getItem(int arg0) {
  14. // TODO Auto-generated method stub
  15. return arg0;
  16. }

  17. @Override
  18. public long getItemId(int arg0) {
  19. // TODO Auto-generated method stub
  20. return arg0;
  21. }

  22. @Override
  23. public View getView(int arg0, View arg1, ViewGroup arg2) {
  24. // TODO Auto-generated method stub
  25. View v = arg1;
  26. LayoutInflater lv = (LayoutInflater) cont
  27. .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  28. v = lv.inflate(R.layout.row, arg2, false);
  29. ImageView iv_android = (ImageView) v
  30. .findViewById(R.id.row_IV_android);
  31. TextView tv_label = (TextView) v.findViewById(R.id.row_TV_detail);
  32. tv_label.setText(" label is " + arg0);
  33. return v;
  34. }
  35. }
  36.  
The getView() is used to inflate the image and the textview to the listview.
getCount() is used to identify the number of items that should be displayed in the list view.
We can consider a arraylist and specify the size of the arraylist so that the getView() will be called for all the list items , thereby displaying a row for each arraylist item.



Now how to use this above code to make it display the listview?


Its similar to setting an adapter for a listview but here the adapter will be an object of the class that extends the BaseAdapter.


i.e.., we use 

listView.setAdapter(new CustomAdapter(this)) instead of  
listView.setAdapter(adapter);

Once have a look at the line 34 :
Here we can see that we are inflating the row.xml file as a view and finally returning the view.


consider the entire code below : (I am not extending a ListActivity. Dont do it)
  1. import android.widget.Toast;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.os.Bundle;
  5. import android.view.LayoutInflater;
  6. import android.view.View;
  7. import android.view.ViewGroup;
  8. import android.widget.AdapterView;
  9. import android.widget.AdapterView.OnItemClickListener;
  10. import android.widget.BaseAdapter;
  11. import android.widget.ImageView;
  12. import android.widget.ListView;
  13. import android.widget.TextView;

  14. public class CustomListsActivity extends Activity implements
  15. OnItemClickListener {
  16. /** Called when the activity is first created. */
  17. ListView listView;

  18. @Override
  19. public void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.main);
  22. listView = (ListView) findViewById(R.id.main_LV_list);
  23. listView.setAdapter(new CustomAdapter(this));
  24. listView.setOnItemClickListener(this);
  25. }

  26. class CustomAdapter extends BaseAdapter {
  27. Context cont;

  28. public CustomAdapter(Context c) {
  29. // TODO Auto-generated constructor stub
  30. cont = c;
  31. }

  32. @Override
  33. public int getCount() {
  34. // TODO Auto-generated method stub
  35. return 5;
  36. }

  37. @Override
  38. public Object getItem(int arg0) {
  39. // TODO Auto-generated method stub
  40. return arg0;
  41. }

  42. @Override
  43. public long getItemId(int arg0) {
  44. // TODO Auto-generated method stub
  45. return arg0;
  46. }

  47. @Override
  48. public View getView(int arg0, View arg1, ViewGroup arg2) {
  49. // TODO Auto-generated method stub
  50. View v = arg1;
  51. LayoutInflater lv = (LayoutInflater) cont
  52. .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  53. v = lv.inflate(R.layout.row, arg2, false);
  54. ImageView iv_android = (ImageView) v
  55. .findViewById(R.id.row_IV_android);
  56. TextView tv_label = (TextView) v.findViewById(R.id.row_TV_detail);
  57. tv_label.setText(" label is " + arg0);
  58. return v;
  59. }
  60. }

  61. @Override
  62. public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
  63. // TODO Auto-generated method stub
  64. Toast.makeText(this, "item clicked is " + arg2, Toast.LENGTH_SHORT)
  65. .show();
  66. }
  67. }

The above code also has an implementation of displaying a toast when a list item is clicked. 


Any suggestions are welcomed.
Please do comment if any problem with the code.

Wednesday, 18 July 2012

Android List View sample

List View  :  As the name suggests it displays items in a list.  The user gets a list of items (a scrollable one when the number of items are not sufficient in the screen )  and when clicked on any item in the list view displays details about the clicked item.
By default the list items are textViews.
If you observe a list view can be seen in Contacts list , messages , songs list etc in a mobile .
A listView can be implemented in Android in two ways.
  1. Using  ListActivity .
  2. Using  ListView in XML file .
Using listActivity

In this we dont write anything in the xml file except the layout. 
My sample xml file looks like this :
   
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
 android:orientation="vertical">
 

Here i am just setting the layout as a linear layout and giving the properties.

And the Activity File looks like this :
  1.  public class ListExampleActivity extends ListActivity implements
  2. OnItemClickListener {
  3. /** Called when the activity is first created. */

  4. ArrayAdapter aa;
  5. ListView lv;
  6. String[] months = { "January", "February", "March", "April", "May", "June", "July" ,"August"       ,"September", "October",  "November" ,"December"};

  7. @Override
  8. public void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);

  10. aa = new ArrayAdapter(this,
  11. android.R.layout.simple_list_item_1, months);
  12. setListAdapter(aa);

  13. lv = getListView();
  14. lv.setOnItemClickListener(this);

  15. }

  16. public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
  17. // TODO Auto-generated method stub
  18. Toast.makeText(this,
  19. "Item is clicked " + ((TextView) arg1).getText() + "  " + arg2,
  20. 600).show();
  21. }
  22. }

Adapters are used in order to bind data with views.
In the similar way i am binding the data (the string array ) with the view (list view) using adapters.
Check the line 1 : we are using a ListActivity. 
       line 13 :  creates a arrayadapter with the data binded to it as the last parameter(months)
       line 17  : getting the default list view .
    line 18  : Setting the click event for the list item. (This will invoke the onItemClick())
    line 23  :   Displays the item that is clicked.



There is no need to change the manifest file for this task.


You can also use XML file to get a list layout.


The output will look something like this