2013

0

Using ListView

Posted on Wednesday, July 10, 2013


How to implement a ListView.


What for?

If you want to show a scrollable list of elements you should implement a ListView control. This is a tricky control, so we’ll see how to use it.We want to show an option list like this:


Resources

First thing, we must  define the needed resources, so, in res/values/strings.xml we’ll create all names needed to show.

<string name="menu_play">Play</string>
 <string name="menu_settings">Settings</string>
 <string name="menu_help">Help</string>
 <string name="menu_statistics">Statistics</string>
You need to fill the listview in runtime, so you’ll do this programmatically.There are different ways to do it. Now we’ll see an easy method. In coming posts we’ll see other implementations.

Method 1: Create an activity that extends ListActivity

ListActivity is a class that displays a scrollable list of items and provides callback methods when the user selects one item. So, if your activity extends this class you have most of the hard work done.You need a place to save the data to show, and also an adapter, that connects the data with the ListView object. We have some standard adapters, as for example ArrayAdapter and CursorAdapter.A simple way to store your data is to have an array of strings that contains the labels you’re going to show. In this case you should use the ArrayAdapter.

1- Without a specific layout

If you do not assign a specific layout for your activity, the activity will show the default one. So, if you don’t need in your layout anything different from the ListView, this is a good option and the easiest one.
Be aware: you don’t have to use the setContentView() because you don’t have a specific layout

public class MenuPrincipalActivity extends ListActivity {
  @Override
 protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
      // here you create an array with your labels
        String[] items = {
              getString(R.string.menu_play),
              getString(R.string.menu_settings),
              getString(R.string.menu_help),
              getString(R.string.menu_statistics),
        };


//and now use an adapter to connect the label string and the listview

ArrayAdapter<String> adapt = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
setListAdapter(adapt);
   }

Note that in this simple method you use the predefined textview R.layout.simple_list_item_1.The result is this:




2- Using a specific layout

If you want to assign a specific layout for your activity, this layout must contain a ListView with the android:id attribute set to @android:id/list. And you also must to assign the layout to the activity via setContentView(), as always.For example, the layout code could be:
<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:background="@color/fondo_pesonalizado"
             android:paddingLeft="@dimen/activity_horizontal_margin"
             android:paddingRight="@dimen/activity_horizontal_margin"
             android:paddingTop="@dimen/activity_vertical_margin"
             android:paddingBottom="@dimen/activity_vertical_margin"
             tools:context=".MenuPrincipalActivity"
       >

   <TextView
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:text="@string/menu_subtitulo"
           android:id="@+id/menu_titulo"
           android:layout_margin="@dimen/dimension_minima"
           android:editable="false"
           android:textAlignment="center"
           android:textStyle="italic"
           android:textColor="@android:color/tertiary_text_light"
           android:gravity="center"/>

   <ListView
           android:layout_width="fill_parent"
           android:layout_height="fill_parent"
           android:id="@android:id/list"
           android:layout_gravity="left|center_vertical"
           android:divider="@android:drawable/divider_horizontal_textfield"
           android:footerDividersEnabled="false"/>

</LinearLayout>

And the activity: 
public class MenuPrincipalActivity extends ListActivity {
@Override
 protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_principal);
      // here you create an array with your labels
        String[] items = {
               getString(R.string.menu_play),
               getString(R.string.menu_settings),
               getString(R.string.menu_help),
               getString(R.string.menu_statistics),
        };


//and now use an adapter to connect the label string and the listview

ArrayAdapter<String> adapt = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
setListAdapter(adapt);
   }
And the result is:

3- Using a specific background layout and item layout 

If you want to use a specific view for each item instead an android default TextView, act as follows:Create an item layout, for example like this:
<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="wrap_content"
           android:id="@+id/icono"
           android:src="@android:drawable/btn_star"
           android:layout_alignParentTop="true"
           android:layout_alignParentLeft="true"
           />

   <TextView
           android:layout_width="wrap_content"
           android:layout_height="fill_parent"
           android:text="New Text"
           android:id="@+id/texto_item"
           android:textSize="@dimen/texto_menu"/>
</LinearLayout>

and now, change the abobe adapter by this one:


ArrayAdapter<String> adapt = new ArrayAdapter<String>(this,R.layout.menu_item,R.id.texto_item,items);
where:
  • menu_item is the specific layout that you have created for your item
  • texto_item is the TextView that you use in the menu_item layout to show the item text
  • items is the array that contains the texts to show.
And the result is:

4ยบ. Create your own adaptator

If you want to customize your item view with other features, for example different icons, you’ll need to create your own adapter.
You must create a new class that extends BaseAdapter. This class must overwrite four methods:
  • View getView(int position, View convertView, ViewGroup parent). This method builds and returns a new View object with the corresponding position. Optionally we can start from a convertview view to generate faster views.
  • int getCount(). Returns the number of elements in the list.
  • Object getItem(int position). Returns data item associated with thespecified position in the data set..
  • long getItemId(int position). Returns the row id associated with the specified position in the list
In this case, act as follows:

public class MiAdaptador extends BaseAdapter {

   private final Activity actividad;
   private final Vector<String> lista;

   public MiAdaptador(Activity actividad, Vector<String> lista) {
       super();
       this.actividad = actividad;
       this.lista = lista;
   }

   public View getView(int position, View convertView,
                       ViewGroup parent) {
       if (position >= 0 && position < lista.size()) {
           LayoutInflater inflater = actividad.getLayoutInflater();
           View view = inflater.inflate(R.layout.menu_item, null,
                   true);
           TextView textView = (TextView) (view.findViewById(R.id.texto_item));
           String texto = lista.elementAt(position);
           textView.setText(texto);
           ImageView imageView = (ImageView) view.findViewById(R.id.icono);

           Context context = view.getContext();

           if (texto.contains(context.getString(R.string.menu_juego))) {
               imageView.setImageResource(android.R.drawable.ic_media_play);
           } else if (texto.contains(context.getString(R.string.menu_ayuda))) {
               imageView.setImageResource(android.R.drawable.ic_menu_help);
           } else if (texto.contains(context.getString(R.string.menu_ajustes))) {
               imageView.setImageResource(android.R.drawable.ic_menu_preferences);
           } else {
               imageView.setImageResource(android.R.drawable.ic_media_next  );

           }

           return view;
       }
       return null;
   }

   public int getCount() {
       return lista.size();
   }

   public Object getItem(int arg0) {
       return lista.elementAt(arg0);
   }

   public long getItemId(int position) {
       return position;
   }
}
And in the activity:

Vector<String> items = new Vector<String>();
    
       items.add(getString(R.string.menu_juego));
       items.add(getString(R.string.menu_ajustes));
       items.add(getString(R.string.menu_ayuda));
       items.add(getString(R.string.menu_estadisticas));


       MiAdaptador adapt = new MiAdaptador(this, items);

       setListAdapter(adapt);

The result is:



On click

To respond to click actions for an specific item you have to overwrite onListItemClick(ListView l, View v, int posicion, long id)

protected void onListItemClick(ListView l, View v, int posicion, long id) {
       String item = (String) getListAdapter().getItem(posicion);
              super.onListItemClick(l, v, posicion, id);
   }

0

Creating an Android Project

Posted on Monday, May 20, 2013

An Android project is a collection of files and folders that contains the source code, configuration and resource files needed to build an Android app. When we start a new project, we need to create the application structure. Let’s see how the Android studio IDE does this for us.

New Project

Once started, Android studio welcomes us showing this screen:

We want a new project, so, to create a new project follow these steps:
  • Select “New Project...” 
  • Fill in the fields as shown below: 

Application name: It is the name that users will see. This name is shown in the Play Store and in Manage Applications.
Module name: This name is only used inside the IDE. You can enter here the same name as above.
Package name: This name is an identifier for your application, which has to be unique and a valid Java package name. It will be the same during all the application lifecycle.
Project location: A folder on your hard disk where the project will be stored.
Minimum required SDK: Is the lowest version of Android that your application will support.
Target SDK: The highest Android version that the app has been tested.
Compile with: The SDK version against which the app will be compiled. It should be the highest latest version of Android.
Theme: The UI style of your app.
Create custom launcher icon: This allows us to change the default launcher icon and use our own.
Create activity: If this box is checked, the IDE will create a default Activity for the app. An Activity represents the presentation layer in Android, it creates a window to place your UI elements that interact with the user. We can have more than one activity, and switch between them in runtime.
Mark this project as a library: A library is a project whose source code and resources will be used in other Android projects. They can’t be used as an application.
  • We have chosen to create a custom launcher icon, so now we can change the default icon by our own image. Play with the options available until you’re satisfied with the result and click Next

  • Now leave the default option “Blank Activity” selected and press Next

  • Leave these option as they are, and press Finish

Android studio will now build the project structure. After this work is completed you will see this screen:

Now we have our first Android project created. In next posts we’ll learn about the structure of a project and the meaning and use of the files and folders created.

0

Creating an Unity launcher for Android Studio


We have installed Android studio, and now we want to be able to run it from the Unity launcher.
First we will create a .desktop file:

gedit ~/.local/share/applications/android_studio.desktop
Then, paste this inside, changing the Icon and Exec values:

[Desktop Entry]
Type=Application
Name=Android-studio
Comment=Android Integrated Development Environment
Icon=/home/<< your username here >>/android-studio/bin/idea.png
Exec="/home/<< your username here >>/android-studio/bin/studio.sh" %f
Terminal=false
StartupNotify=true
StartupWMClass=jetbrains-android-studio
Categories=Development;IDE;Android;
Now open the folder with Nautilus:
nautilus ~/.local/share/applications


and drop android-studio.desktop to the desired position in launcher.

0

Installing Android Studio in Ubuntu 13.04

Go to http://developer.android.com/sdk/installing/studio.html and download Android studio for linux. It will download a tar file in your Downloads folder. Once downloaded, open Nautilus, navigate to Downloads folder, right click in android-studio-bundle-130.677228-linux and select "extract here".
Now you have a new folder named "android studio". Move this folder to your Home folder.
To run the IDE, open the terminal and type:

cd android-studio/bin
./studio.sh
If you are on Ubuntu default installation, using OpenJava, you will see this warning:

If you press Enter Android studio will start with this window:

Troubleshooting.

Installing Oracle Java SDK:
There are two ways for installing Oracle Java SDK.

First method.

First the easy one. Open the console and type:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer
Ok, now let's check the java version installed. Type:
java -version
and you should see something like:
java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b11)
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)

Second method:

Go to http://www.oracle.com/technetwork/es/java/javase/downloads/index.html and download Java JDK. Be sure to download the tar.gz corresponding to your architecture (Linuxx86 or Linuxx64).
Uncompress the file:
tar -xvf jdk-7u21-linux-i586.tar.gz (32bit)
tar -xvf jdk-7u21-linux-x64.tar.gz (64bit)
Now let's move the uncompressed folder to /usr/lib
sudo mkdir -p /usr/lib/jvm
sudo mv ./jdk1.7.0_21 /usr/lib/jvm/jdk1.7.0
Now run in terminal:
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0/bin/javaws" 1
Change ownership and permissions:
sudo chmod a+x /usr/bin/java
sudo chmod a+x /usr/bin/javac
sudo chmod a+x /usr/bin/javaws
sudo chown -R root:root /usr/lib/jvm/jdk1.7.0
run:
sudo update-alternatives --config java
and choose the option corresponding to /usr/lib/jvm/jdk1.7.0/bin/java
do the same for
sudo update-alternatives --config javac
sudo update-alternatives --config javaws
Now check the version with
java -version

0

Let's get started. Installing Android studio.

Posted on Saturday, May 18, 2013


The first thing you'll need to start developing Android apps is an IDE. An IDE (integrated development environment) is a tool that provides, in an unique application, such things as a compiler, a code editor, a debugger, a GUI designer, and many other facilities for development.
If you are an experienced Android developer, you may be familiar with Eclipse. Eclipse is an multilanguaje IDE that has been the default tool for Android development so far. During the Google I/O 2013 event, Google has launched a specific IDE for development, based on the community edition of the Java IDE IntellijIDEA.
This software is called Android Studio. The version available to download right now is v0.1, which is a Early Access Preview. This means that there are features not implemented yet, and that the application may have bugs and should not be used in a production environment. Nevertheless, it seems like Google will be pushing this tool as the default development environment for Android applications.
So, as good developers trying to learn as much as possible, and to be up to date, let's see how to install Android studio.


Installing Android studio. 

First of all, you need to download Android studio from developer.android.com. Get the version that match your operating system:
download android studio
Now you have to install it. Let's see how to do it for Windows, and in a future post we will see how to do it for ubuntu.
Double click the downloaded .exe file to let the installation process begin.
Android studio should detect your JDK installation folder:

Be sure you have Java JDK installed in your system previously. If you are running a 64bit version of Windows, Android Studio may not be able to find the correct path to your JDK folder. Be sure you have an environmental variable set up with the following parameters:
name: JAVA_HOME or JDK_HOME
value: your path to your JDK folder, usually "C:\Program files\Java\jdk1.7.0_21"
Now the installation process is finished. You can run the program and import a project or create a new one.