Android ImageButton Example

        

         The name of this element speaks for itself, ImageButton is basically just a clickable image:) There are three things that you are going to need to create an ImageButton:

1. Design your button

         To do this you can use any software that you are comfortable with, it can be Paint or Microsoft Word, or Photoshop and PagePlus for something more sophisticated:) You can also find some very nice ready to use buttons on the internet (for example http://www.iconarchive.com is a good place to take a look at), just make sure to check the licence:) I have created a very simple button, that looks like this: 




This image needs to be placed in the  res\drawable directory of your project! 

2. Decide what action you want your button to perform 

         This directly depends on your application needs. In this tutorial we will be dialing a number on click (which explains why my button says "Call" on it=)).

3. Code it!

This is very simple:)

a) First thing we need to do here is to modify our xml file, which you can find in res\layout directory by the nameactivity_main.xml (or something similar, the name can vary). Here is a full code for our activity_mail.xml file:

 <?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="vertical"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:gravity="center"  
   android:background="#B6B6B4" >    
   <EditText  
     android:id="@+id/contact_number"  
     android:inputType="number"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:hint="@string/enter_nember" />  
   <ImageButton   
     android:id="@+id/call_button"  
     android:contentDescription="@+id/call"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:background="#B6B6B4"  
     android:src="@drawable/call_button"  
     />  
 </LinearLayout>  

             Now let me explain the code a little. We are using the LinerLayout here since its very simple and easy to use)  In this linear layout we place two elements: EditText that we need for our user to be able to enter a number that he wants to dial (fell free to get rid of it if your button will be performing some other action) and ImageButton element, here we  need to specify the location of our image, which is android:src="@drawable/call_button".

b) Next thing that we need to do is to fill with code our java class file. By default the name of this class will beMainActivity.java and it is located in the src\your_project_package_name\MainActivity.java directory. The full code for it is the following:

 package com.examples.a_tuts;  
 import android.net.Uri;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.EditText;  
 import android.widget.ImageButton;  
 import android.app.Activity;  
 import android.content.Intent;  
 public class MainActivity extends Activity {  
      private String edittext_value;  
      private EditText number;  
      private ImageButton sleepingSmiley;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
           number = (EditText) findViewById(R.id.contact_number);  
           sleepingSmiley = (ImageButton) findViewById(R.id.call_button);  
           onButtonClick();  
      }  
      private void onButtonClick(){  
           sleepingSmiley.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                     edittext_value = number.getText().toString();  
                     Intent i = new Intent(Intent.ACTION_CALL);  
               i.setData(Uri.parse("tel:" + edittext_value));  
               startActivity(i);                 
                }  
           });  
      }  
And some explanation: 

             In the beginning in onCreate method we let Android know what elements we will be using, both EditText andImageButton elements are found by their id that we have specified in our activity_main.xml file.  
                Then we set OnClickListener to our ImageButton and place corresponding code into onClick method. Since my goal here was to dial a number, I first extracted a value that a user entered in the EditText element and used Intent.ACTION_CALL to dial a number:) Now if your button is supposed to perform some other action just replace the come inside the onClick method with something relevant:) 

That's it! 

oh, and here is a DEMO:

Source code

               
          Thank you for reading my blog, hope this was helpful and I also hope to see you here again:) Have a great day)

Android Spinner

Android Spinner


    
 In this tutorial I'll show you three things: 
  • How to add a spinner to your application layout;
  • How to populate your spinner with an array from strings.xml file;
  • How to handle user's selection.

Lets get started then:)

1. Adding spinner to your application layout
    
           To do that you will need to add a spinner element to your xml file, which is located in the res\layout directory:
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   tools:context=".MainActivity" >  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="@string/color_hint"  
     android:textSize="20sp" />  
   <Spinner   
     android:id="@+id/colorSpinner"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:scrollbars="vertical"  
     android:entries="@array/color_array"  />  
 </RelativeLayout>  

           As you see I have highlighted android:entries="@array/color_array" line. In this line we are defining where the entries for our spinner element are supposed to be taken from, in this case we will populate the spinner with an array. 

2. Populating Spinner with an array from strings.xml file

         The first thing that we need to do here is to create an array. Open res\values\strings.xml file and add the following code to it:
 <string-array name="color_array">  
     <item>Yellow</item>   
     <item>Pink</item>    
     <item>Purple</item>  
     <item>Red</item>       
   </string-array>  

        We now have an array that contains four items: Yellow, Pink, Purple and Red (which is kind of obvious, I know:) After creating this array we should be able to find it by its name, which we did before in our main xml file:
  android:entries="@array/color_array"   

3. Handling user's selection
         To handle user's selection we will need to edit MainActivity.java file like this:

  package com.example.spinnerapp;  
 import android.os.Bundle;  
 import android.app.Activity;  
 import android.content.Context;  
 import android.view.View;  
 import android.widget.AdapterView;  
 import android.widget.AdapterView.OnItemSelectedListener;  
 import android.widget.Spinner;  
 import android.widget.Toast;  
 public class MainActivity extends Activity {  
      private Spinner ourcolorspinner;   
      private String selection;   
      final Context context = this;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
           ourcolorspinner = (Spinner) findViewById(R.id.colorSpinner);  
           listenerMethod();  
      }  
      private void listenerMethod() {  
           // TODO Auto-generated method stub  
         ourcolorspinner.setOnItemSelectedListener(new OnItemSelectedListener()   
         {  
       @Override  
       public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)   
       {  
         selection = (String) parentView.getItemAtPosition(position);  
         Toast.makeText(context, "You seleceted " + selection + ".", Toast.LENGTH_LONG).show();  
       }  
       @Override  
       public void onNothingSelected(AdapterView<?> parentView)   
             {}});  
      }}  
      
        As you can see the listenerMethod() method was added. In it we are setting an OnItemSelectedListener to our Spinner and inside the onItemSelected method we inserted a code, that lets us get the value of an item that was selected as well as show a little notification about it:)

DEMO
Android Spinner example
Source Code

Android Button Example


In this tutorial you will learn:
  • How to add a button element to your application layout
  • How to change button's color
  • How to react to user pressing a button.



1. Adding button element to your application layout

                  To do this you need to modify your xml layout file (which is located in the res/layout directory). In this tutorial I'll show you how to add four different size and color buttons, but if you only want to add one button feel free to leave all the other ones out:)
activity_main.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:orientation="vertical"  
   android:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   android:background="#696969"  
   tools:context=".MainActivity" >  
   <Button   
     android:id="@+id/yellow_button"  
     android:layout_width="fill_parent"  
     android:layout_height="60dp"  
     android:background="#FFD700"  
     android:text="@string/yellowButton"/>  
   <TableRow  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content" >  
    <Button   
     android:id="@+id/Blue_button"  
     android:layout_width="fill_parent"  
     android:layout_height="80dp"  
     android:layout_marginRight="5dp"  
     android:layout_marginTop="10dp"  
     android:background="#B0C4DE"  
     android:layout_weight="1"  
     android:text="@string/blueButton"/>  
    <Button   
     android:id="@+id/Green_button"  
     android:layout_width="fill_parent"  
     android:layout_height="80dp"  
     android:layout_marginLeft="5dp"  
     android:layout_marginTop="10dp"  
     android:layout_weight="1"  
     android:background="#90EE90"  
     android:text="@string/greenButton"/>    
   </TableRow>  
     <Button   
     android:id="@+id/pink_button"  
     android:layout_width="fill_parent"  
     android:layout_height="60dp"  
     android:layout_marginTop="10dp"  
     android:background="#F08080"  
     android:text="@string/pinkButton"/>  
 </LinearLayout>  

            I am using TableRow element here so it would be easier to position two buttons in one row) Using android:layout_weight we make our buttons equally big, so they would occupy equal amount of space in this row. 

2. Changing color

           It is super easy to change button's color, you simply need to specify the value of android:background accessory. To do that you need to use HEX color codes. There are plenty of websites where you can find codes for all the colors out there, I personally use this table http://www.w3schools.com/tags/ref_color_tryit.asp?color=LightGrey. As you can see in the activity_main.xml I have added android:background accessory to each of our buttons:
  • Yellow android:background="#FFD700"
  • Blue android:background="#B0C4DE"
  • Green android:background="#90EE90"
  • Pink android:background="#F08080" 
3. Handling user input


           To handle user's input we need to go to MainActivity.java file and add some stuff to it:) First thing we need to do is to initialize  all our buttons and then set onClickListener to all of them:

 package buttonexample.tut.com;  
 import android.os.Bundle;  
 import android.app.Activity;  
 import android.content.Context;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.Button;  
 import android.widget.Toast;  
 public class MainActivity extends Activity {  
      private Button yellowB;  
      private Button greenB;  
      private Button blueB;  
      private Button pinkB;  
      final Context context = this;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
           yellowB = (Button) findViewById(R.id.yellow_button);  
           greenB = (Button) findViewById(R.id.Green_button);  
           blueB = (Button) findViewById(R.id.Blue_button);  
           pinkB = (Button) findViewById(R.id.pink_button);  
           onClickReactor();  
      }  
      private void onClickReactor() {  
           // TODO Auto-generated method stub  
           yellowB.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                     Toast.makeText(context, "You pressed a yellow button.", Toast.LENGTH_SHORT).show();                      
                }  
           });  
           greenB.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                     Toast.makeText(context, "You pressed a green button.", Toast.LENGTH_SHORT).show();  
                }  
           });  
           blueB.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                     Toast.makeText(context, "You pressed a blue button.", Toast.LENGTH_SHORT).show();  
                }  
           });  
           pinkB.setOnClickListener(new OnClickListener() {  
                @Override  
                public void onClick(View v) {  
                     Toast.makeText(context, "You pressed a pink button.", Toast.LENGTH_SHORT).show();  
                }  
           });  
      }  
 }  

You can place any other code in the onClick method, that depends on your application needs:)

DEMO
Android Button Example
Android Button Example
Source code

Android ListView Example


In this tutorial I will show how to create a ListView and fill it with data. 
1. Creating a row layout

             First thing that we need to do is to create a row layout that will specify the way each row of our ListView is going to look like. To do that we need to create a new xml file (ringht click on the res folder of your project New->Android xml file) and name it row. Add the following code to your new row.xml file:

 <?xml version="1.0" encoding="utf-8"?>  
 <TextView   
      xmlns:android="http://schemas.android.com/apk/res/android"  
      android:textIsSelectable="true"  
      android:id="@+id/r_text"   
      android:layout_width="fill_parent"  
      android:layout_height="fill_parent"  
      android:padding="10dip"  
      android:textColor="#ffffff"  
      android:textSize="17sp"/>  

2. Creating a ListView

Now we need to add a ListView element to our acitivy_main.xml file:
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
          android:layout_width="match_parent"  
          android:orientation="vertical"  
          android:layout_height="match_parent"  
          android:background="#000000">   
 <ListView android:id="@+id/android:list"  
           android:layout_width="fill_parent"  
           android:layout_height="fill_parent"/>  
 </LinearLayout>  

3. Adding items to ListView
        
       The last thing that we need to do is to modify our Activity. Open MainActivity.java file of your project and modify the code like this:
  package listviewexample.tuts.com;   
  import android.os.Bundle;   
  import android.app.ListActivity;   
  import android.widget.ArrayAdapter;  
  import java.util.ArrayList;  
  import java.util.Collections;  
  import java.util.List;   
  public class MainActivity extends ListActivity {   
    private String[] items;  
    private List<String> list;  
    private ArrayAdapter<String> adapter;  
    @Override   
    protected void onCreate(Bundle savedInstanceState) {   
       super.onCreate(savedInstanceState);   
       setContentView(R.layout.activity_main);   
       fillData();   
    }   
    private void fillData() {   
       String[] items = new String[] {"Monday", "Tuesday", "Wednesday",    
               "Thursday", "Friday", "Saturday", "Sunday"};   
       list = new ArrayList<String>();  
       Collections.addAll(list, items);  
       adapter =   
          new ArrayAdapter<String>(this, R.layout.row, R.id.r_text, list);    
       setListAdapter(adapter);        
    }   
  }   
Let me add some code explanation too:

  • because we want to display a ListView our Activity became a ListActivity:)
  • in the fillData() method we first create an array of strings, that will later be placed in the list
  • then we created an ArrayAdapter of string types and specified the following parameters of its constructor:  
  1. current context
  2. row layout that has to be used for each row
  3. the ID of the TextView, in which our items will be placed (this ID is taken from row.xml file
  4. items that need to be placed in it
  • then we called setListAdapter() to let our ListActivity know how to fill the ListView
  • Thats it!=) 

DEMO
Android ListView example
Android ListView Example

Source code


Thank you for reading my blog!:)