I don't like inline listeners, and only Android 2 and up support Android:onClick in layout XML,
I have to programming under 1.5, this article is very helpful!


Implementing Listeners in your Android/Java application

I’ve seen many people asking how to implement Listeners in their applications. Implementing a Listener is quite easy. There are 3 ways to implement an Listener and the have their advantages and disadvantages.

The tree way to implement Listeners are

  • Inline Implementation
  • Using the implements keyword
  • By using variables

We’ll use our good old LoginExample application, created in previous tutorial which can be found at Android: Your first Android Application.


Inline Implementation

The first way, to implement an listener is by using Inline Implementation. In Inline Implementations we create an anonymous listener, define and pass it the the setLisener functions in the same step.

We did this already in our First Android Application Tutorial.

01package com.tseng.examples;
05public class LoginExample extends Activity {
06    /** Called when the activity is first created. */
07    @Override
08    public void onCreate(Bundle savedInstanceState) {
09        super.onCreate(savedInstanceState);
11    ...
13        // Set Click Listener
14        btnLogin.setOnClickListener(new OnClickListener() {
15            @Override
16            public void onClick(View v) {
17                // Check Login
18                String username = etUsername.getText().toString();
19                String password = etPassword.getText().toString();
21                if(username.equals("guest") && password.equals("guest")){
22                    lblResult.setText("Login successful.");
23                } else {
24                    lblResult.setText("Login failed. Username and/or password doesn't match.");
25                }
26            }
27        });
28        btnCancel.setOnClickListener(new OnClickListener() {
29            @Override
30            public void onClick(View v) {
31                // Close the application
32                finish();
33            }
34        });
35    }

As we see, we create an anonymous class there by adding { … code … } behind the new OnClickListener interface and implementing the necessary onClick(View v) method.


  • Small and tidy
  • Easy to implement
  • Less overhead


  • Inflexible
  • Can’t be reused
  • Can be a bit harder to maintain


Inline implementations are usually used for short 1-time methods, for example if you have a button which closes the application or which displays, you don’t need to add an implementation to your class or create a variable, making your code less readable.

Using the “implements” keyword

The second method to implement an Listener is by adding an interface to your base class. In java you can do this by adding “implements Interfacename” to the class declaration.

01package com.tseng.examples;
05public class LoginExampleImplements extends Activity implements OnClickListener {
07    /** Called when the activity is first created. */
08    @Override
09    public void onCreate(Bundle savedInstanceState) {
10        super.onCreate(savedInstanceState);
12    ...       
14        // Set Click Listener
15        btnLogin.setOnClickListener(this);
16        btnCancel.setOnClickListener(this);
17    }
19    @Override
20    public void onClick(View v) {
21        if(v==btnLogin) {
22            // Check Login
23            String username = etUsername.getText().toString();
24            String password = etPassword.getText().toString();
26            if(username.equals("guest") && password.equals("guest")){
27                lblResult.setText("Login successful.");
28            } else {
29                lblResult.setText("Login failed. Username and/or password doesn't match.");
30            }
31        } else if(v==btnCancel) {
32            // Close the application
33            finish();
34        }
35    }

As we can see, the “onClick(View v)” is being declared inside our LoginExample class and additionally we set the listener by passing a reference to our class to by using btnLogin.setOnClickListener(this);. This works, because we implemented this interface within our class public class LoginExampleImplements extends Activity implements OnClickListener. You may also have noticed, that we add the same listener to both buttons. Because both of the buttons use the same listener, we need to differentiate which one was clicked. This can be done by comparing the View v reference with the Button btnLogin reference as seen below:

1if(v==btnLogin) {
2    // Check Login
3    ...
4} else if(v==btnCancel) {
5    // Close the application
6    ...


  • Methods/Listener can be reused in many different widgets
  • Code of multiple Listeners is located in the same section of code
  • Can be used to create one method for similar Listeners


  • Can contain much unnecessary and untidily code, if the actions executed are to different and you have to add an if / elseif / else blocks, making the code hard to read
  • You can only have one implementation of this Listener per class


This method is best used, when you have multiple widgets/elements using same or similar listeners (i.E. doing a calculation or check on a click or key press). The example above is not the best example on the usage of the implement method. Let’s imagine, you have a calculator and have 14 buttons  and you want to update the formula you entered after every calculator button is pressed, you could implement it in the following way shown below.

01package com.tseng.examples;
04import android.os.Bundle;
05import android.view.View;
06import android.view.View.OnClickListener;
07import android.view.View.OnKeyListener;
08import android.widget.Button;
09import android.widget.EditText;
10import android.widget.TextView;
12public class CalculatorExample extends Activity implements OnClickListener {
13    ...
15    @Override
16    public void onClick(View v) {
17        if(v==btnCalculate) {
18            // Parse and calculate formula
19            String formula = etFormula.getText().toString();
20            Double result = performCalculation(formula);
22            // Update the result TextView
23            tvResult.setText(Strint.valueOf(result));
25            // End it as we don't need or want to update the Formula field
26            return;
27        }
29        // Get the button
30        Button button = (Button)v;
32        // Get the String/Button descritpion
33        String strToAppend = button.getText().toString();
35        // Update Formula
36        etFormula.append(strToAppend);
37    }

You could add this Listener to every of the calculators button and only need to define one Listener. When the buttons are clicked, the button text (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +, –, /, * etc.) will be added to the TextView containing the formula. However, if you press the calculate button, it won’t add a = to the formula, but will instead perform the calculation.

Another very good implementation of this is, if you want to validate the input in a TextField altough there are other way in Android by using the TextView.setFilters(…) Method, but this is another topic.

This is best used when you’re creating your own widgets and want to to handle clicks (assuming there are only few clickable elements there)

By using Variables

This one is very similar to the previous one, with the difference that you don’t add the implementation to your class, but instead hold a reference to the Listener in a variable.

In our LoginExample it would look like this

01package com.tseng.examples;
05public class LoginExampleVariableImplementation extends Activity {
06    ...
08    OnClickListener myClickListener = new OnClickListener() {
09        @Override
10        public void onClick(View v) {
11            if(v==btnLogin) {
12                // Check Login
13                String username = etUsername.getText().toString();
14                String password = etPassword.getText().toString();
16                if(username.equals("guest") && password.equals("guest")){
17                    lblResult.setText("Login successful.");
18                } else {
19                    lblResult.setText("Login failed. Username and/or password doesn't match.");
20                }
21            } else if(v==btnCancel) {
22                // Close the application
23                finish();
24            }
25        }
26    };
28    /** Called when the activity is first created. */
29    @Override
30    public void onCreate(Bundle savedInstanceState) {
31        super.onCreate(savedInstanceState);
33    ...
35        // Set Click Listener
36        btnLogin.setOnClickListener(myClickListener);
37        btnCancel.setOnClickListener(myClickListener);
38    }

Basically we create it anonymous Listener with the difference that we hold a reference to it. This allows us to add this Listener to more than only one widget. The main difference to the implements keyword method is, that we can have more than one Listener inside our class declared and use them more than once.


  • Can be reused
  • You can have more than one Listener of the same kind in your class
  • You can keep your listeners organized in one place, making your code easier to read


  • Too many listeners can make the code rather complicated to read


This is best to use if you have different Listeners for the same action i.e. 2 different OnClickListener which do a completely different task.

Another very important usage for this variant is if you’re implementing your own Listeners to your widgets, you could have a variable which can be assigned by the users of your widgets

01package com.tseng.examples;
04import android.os.Bundle;
05import android.view.View;
06import android.view.View.OnClickListener;
07import android.view.View.OnKeyListener;
08import android.widget.Button;
09import android.widget.EditText;
10import android.widget.TextView;
12public class MyWidget extends View {
13    ...
15    OnClickListener myClickListener = null;
17    /** Called when the activity is first created. */
18    @Override
19    public void onCreate(Bundle savedInstanceState) {
20        super.onCreate(savedInstanceState);
22        ...
24    }
26    public void setOnClickListener(OnClickListener listener) {
27        myClickListener = listener;
28    }
30    private onClick(View v) {
31        // Check if Listener was set and call the onClick Method
32        if(myClickListener!=null)
33            myClickListener.onClick(v);
34    }
35    private void handleEventsMethod() {
36        ...
37        // handle clicks
38        onClick(this);
39    }

This allows us to dynamically set the Listener to our widget without knowing what the listener will actually do with the click, as it can be implemented in any way the user or programmer wants it to be.


So there are no “right” ways to implement a Listener. It all depends on the situation and/or your personal preferences.

Method Recommended usage
Inline Best to use for short and one time only listeners, like closing an application or displaying an message or call another Activity/Dialog
implements-keyword If you have only one listener in your class (i.e. your own widget) or the listeners shares a fairly similar code/task, like the Calculator Example above
Variables If you have many Listeners with very different codebases and tasks or creating your own widget and want to allow your users to handle the events (i.e. click or key press events).

Categories: Android | Java

this is what I did:
Step 1:
first download the source code from

step 2:
 copy the \base\core\java\android\ to android-sdk-windows\platforms\android-8\sources
 you need create the sources folder yourself.

Step 3:
 restart the Eclipse.

for 1.5 source code,
please see this article:

Categories: Android

Ctrl + F11 to switch the View direction (Port <-> Land)

Categories: Android

Android Froyo 2.2 新特性总结

作者:【Android手机网原创】   来源

    支持多点触控功能,目前市面上在售的大部分Android手机都采用了电容式触控屏,硬件上已经加入了对多点触控的支持。如今Android Froyo 2.2中加入了多点触控功能则可能致使大部分安致手机都具备多点操控功能。
    更大的运行内存,这个新特性其实是对系统性能进行的优化,Froyo 2.2中加入了类似CyanogenMod的ROM的释放RAM运行内存的技术,程序运行将更流畅。
    3D性能的优化,3D性能将成为未来智能手机运行应用程序所必须的性能之一,Android 2.2冰酸奶改进了对OpenGL ES 2.0的支持 ,3D性能更为强大。
    Flash 10.1的加入,Flash Android版本的推出时间还掌握在开发商Adobe手中,如果Adobe开发成熟或许Flash 10.1会直接内置到Android 2.2中,如果还没有开发完毕,或许就只能通过自己下载或者OTA更新推送了。
    轨迹球LED指示灯变色功能。这个功能的加入让原来已经人性化十足的Android加入了一份贴心。据说本来在Nexus One搭载的2.1系统里就应该有,但最后Google移除了这个功能,这次在Froyo 2.2中加入。
    FM功能支持,目前已知的内置FM芯片的Android手机有HTC的Desire和Incredible,在2.1固件中是不支持FM收音机功能的,但是升级了Froyo 2.2之后将会激活FM功能。

Categories: Android

Android 2.2七大特色功能

作者:【Android手机网原创】   来源
    Android的下一个版本是Google主导开发的2.2 Froyo,巨大的冰冻酸奶雕像在谷歌山景城总部已经准备好了,正准备在本月19日的I/O大会上掀开帷幕。Android手机网这次为您带来的是2.2 Froyo操作系统让中最令人期待的七大特色功能。
    1.最令人期待的功能之一就是在2.2 Froyo中加入了对USB/蓝牙键盘的支持。众所周知,Android系统主要是靠全触控操作来控制,对于一些商务功能(比如快速的输入)就需要硬键盘 来实现了,但是并不是所有Android手机都具备QWERTY全键盘,因此USB/蓝牙键盘的支持就显得非常必要了,毕竟按照目前来看苹果iPAD的最 大竞争对手就是Android平板设备,加上蓝牙和USB键盘的支持之后将会大幅提升竞争力。
    2.三种性能和能耗模式的选择。对于手机来说,最重要的地方莫过于手机的待机能力,全新的Android 2.2为我们带来了三种性能和能耗模式的选择,分别是高/正常/低。用户通过这些模式的切换选择就能手动的控制能耗,延长手机待机续航时间,
    3.第三大改变则是Android Market的升级。全新的Market具备更多中付费程序支付模式,可以直接通过信用卡和PayPal账户进行支付,甚至我们还能先购买程序,到月底一起结账。
    而所有的程序都新增了“全部升级”或“自动升级”选项,选择之后,当该程序的版本升级,Android 2.2 Froyo就会自动进行升级,为用户节省了很多的时间。
    第三个方面,就是增加了PC端直接访问Android Market的功能,无形中为用户节省了很多流量费用。成为继WIFI之后的另一种节省成本访问方式。
    4.可选择性的系统补丁升级。新版本的Android 2.2可以像电脑的Windows系统一样在可更新补丁列表中选择自己需要的补丁进行升级,而不是自动全部升级,人性化再次提升一个等级。
    6.音乐播放器的全面升级。用过Android系统音乐播放器的朋友,如果对这个功能组件用一个字进行评价的话,那就是“烂”。不但界面不美观,在功能方 面也缺少很多比较实用的功能。2.2 Froyo中对此功能组件进行了全面升级,赋予音乐播放器一个更好的文件系统和界面UI,满足人们多种方式的使用需求。
    7.离线Google Maps地图。现在通过一些第三方程序可以将Google Maps地图文件下载到内存卡中,再通过手机的GPS模块实时定位导航,如今在即将发布的Android 2.2版本系统中直接内置了这个功能,为用户提供了最大的方便。

Categories: Android

My boss let me do some research on Android, and want to see how effect it need and if many people will download and use it.

after set up development environment, and running the Hello world, My next step is make the GUI look nicely and give my application our icon.

Do some search and find how to assigning a icon to my application:

Assigning an icon to your Android application just takes a minute.  Actually creating the icon may take a bit longer. :P

  1. Create a 48×48 PNG and drop it into /res/drawable.  The name of this file is usually “icon.png”.
  2. Open your AndroidManifest.xml.
  3. Right under the root “manifest” node of the XML, you should see the “application” node.  Add this attribute to “application”. (The “icon” in “@drawable/icon” refers to the file name of the icon.)

Your app is now iconned.

(Posted in Android by MrSqueezles at January 31st, 2009.)

Categories: Java | Android