Quick tests
Sometimes a project demands that we code in a thorough, “belt and suspenders” fashion.
However many times it just isn’t necessary to go through all of the trouble — particularly when you’re trying out a new API for the first time and you really don’t need to build a production-ready project.
I find myself often throwing together a quick app to test something — in most cases I create a single button to initiate the test.
This article takes a look at three ways to accomplish this task. Pick the one which is right for you and the project you are working on.
Generally speaking an Android application’s UI is defined within an XML layout file. When you create a new project in Eclipse, the Android Developer Tools provide a layout (main.xml) that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
Now, let’s add a Button widget to the mix,named “Hit Me”.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hit Me"
andorid:id="@+id/btnHitMe"
/>
This Button needs to trigger an action in our code, so let’s have a look at the Java code behind this user interface.
Note that in order to work with a Button in code we need to import android.widget.Button.
import android.widget.Button;
And to wire up the handlers we define an instance of the android.widget.Button at the class level:
private Button btnHitMe = null;
Now, let’s get a reference to the widget within the onCreate method of our Activity class:
btnHitMe = (Button) findViewById(R.id.btnHitMe);
The R.id.btnHitMe enumeration is automatically generated by the Android Developer Tools when the main.xml file is modified and saved. When the optional android:id attribute is included in the definition of the widget as shown in the earlier listing, the ADT automatically creates the enumerations to identify this widget throughout the project. These values are stored in R.java. Never modify this file by hand — it is a fool’s errand as it is constantly being re-written by the tools.
Once we have a valid reference to the widget from findViewById, we need to set up the click handler to process Button interaction:
bHitMe.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
// process the button tap
}
});
Within this anonymous class we implement whatever code is relevant for our test.
Here is the complete code for this anonymous handler approach, choosing to display a Toast notification when the Button is tapped, or “clicked”.
package com.msi.linuxmagazine.hotwiregui;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
public class HotWireGui extends Activity {
private Button btnHitMe;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnHitMe = (Button) findViewById(R.id.btnHitMe);
btnHitMe.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
// process the button tap
(Toast.makeText(HotWireGui.this,"Clicked Me!",Toast.LENGTH_LONG)).show();
}
});
}
}
This code works fine though some Java folks might argue that anonymous classes are evil or some such other religious view about this code. Perhaps it is a bad habit, but not a topic for today’s discussion.
Evil or not, I prefer to not write all of this code so I tend to “cut-n-paste” this code from one project to the next. Let’s look at another approach — having the class itself be the “listener”.
Class level listener
The next approach to look at is where we have the Activity class implement the OnClickListener rather than employing an anonymous class.
To do this we need to import the Interface:
import android.view.View.OnClickListener;
Then we indicate that the class implements the Interface:
public class HotWireGui extends Activity implements OnClickListener
Of course, then we must actually implement this interface which means that we need a method named onClick which takes a single View argument. The full code is shown here:
package com.msi.linuxmagazine.hotwiregui;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class HotWireGui extends Activity implements OnClickListener{
private Button btnHitMe;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnHitMe = (Button) findViewById(R.id.btnHitMe);
btnHitMe.setOnClickListener(this);
}
public void onClick (View v) {
// process the button tap
if (v.getId() == R.id.btnHitMe) {
(Toast.makeText(HotWireGui.this,"Clicked Me in onClick method!",Toast.LENGTH_LONG)).show();
}
}
}
Things to note about this code:
- We still have to define the Button and get a reference to it with the findViewById() method.
- We still need to setup the “OnClickListener” — though this time we simply pass in this.
- The OnClick method can either make an assumption about the View it is receiving if there is only one we are working with, or we need to do some sort of check on the passed-in View instance to determine which code to run. This is of course only relevant if the Activity has to respond to more than one view that can raise the onClick event.
From a read-ability perspective, this approach may be easier as we’re not dealing with the nameless anonymous class. When there are many Buttons in play a bunch of calls to findByView followed by setOnClickListeners and the accompanying enclosed methods can be a bit tedious to sift through in the code — let alone write in the first place. With this single click handler and comparisons the code can be a bit easier to read and maintain. One downside however is that this one method is likely going to handle ALL clicks in the Activity.
OK, so let’s say you’re super lazy and you just don’t even want to do this modest amount of coding?
What can we do to wire up a Button without:
- Implementing the OnClickListener interface, or
- Without importing the Button class, or
- Without finding the view and assigning the listener for each button in Java code?
Can this really be done? Yes — let’s look at a really quick and dirty way to implement a click handler for an Android Button to help you build simple apps without the fuss of all of that boiler-plate code.
Cheating?
We start by looking at the code — there’s just not much to it so we’ll just walk through it quickly.
We start out with the Button definintion in the layout file — we need to make a small change there. Don’t worry, it’s worth it.
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Hit Me”
android:id=”@+id/btnHitMe”
android:onClick=”HandleButton”
/>
This looks identical to the version we saw earlier with the exception that there is a single addition of a new attribute, namely android:onClick.
The value assigned to this attribute, HandleButton, refers to a developer-supplied method with the “onClick” signature of (View v).
Let’s have a look at the Java code implementing this Activity.
package com.msi.linuxmagazine.hotwiregui;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class HotWireGui extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void HandleButton(View v) {
if (v.getId() == R.id.btnHitMe) {
(Toast.makeText(HotWireGui.this,"Hot wired Button!",Toast.LENGTH_LONG)).show();
}
}
}
Note that the Button class is not imported. There is no definition of a Button instance. No calls to findViewById. No calls to setOnClickListener. No extra sets of curly braces to match up on the anonymous class’ onClick handler, etc.
We must however provide a method with the correct signature. In this case we’ve called it HandleButton.
In the code we evaluate the passed-in View instance and check it’s Id. If it matches the one we’re looking for we implement our code. This same routine can handle an arbitrary number of Button’s on the screen.
The other neat thing here is that we can have an arbitrary number of these methods, named however we like, to further segregate the code for the Buttons. Want a different click handler name for a set of Buttons? No problem, just reference it appropriately in the XML layout file for the android:onClick attribute.
I stumbled upon this approach when writing a remote control for a robot with a bunch of buttons. Coding all of that boiler-plate code just bothered me and I was pleased to settle upon this approach.
Is it right for you? Perhaps. Let me know what you think.
Comments on "Wiring Up Android Buttons"
Usually posts some very exciting stuff like this. If you are new to this site.
The time to read or take a look at the content material or sites we have linked to below.
Normally I don’t read article on blogs, however I would want to
state that this write-up very pressured me to take a look at and do so!
Your writing taste has become amazed me. Thanks a lot, very nice article.
Here is my web site CharitaTFava
Always a massive fan of linking to bloggers that I really like but don?t get a great deal of link love from.
Every when in a while we pick blogs that we read. Listed beneath would be the most current sites that we select.
Below you will come across the link to some sites that we think you should visit.
Although sites we backlink to below are considerably not connected to ours, we really feel they may be essentially worth a go by way of, so possess a look.
Here is a superb Blog You might Find Interesting that we encourage you to visit.
We like to honor several other web websites around the web, even though they aren?t linked to us, by linking to them. Under are some webpages worth checking out.
Check beneath, are some totally unrelated sites to ours, nonetheless, they are most trustworthy sources that we use.
Below you?ll discover the link to some web-sites that we assume it is best to visit.
Check beneath, are some absolutely unrelated sites to ours, nevertheless, they are most trustworthy sources that we use.
Very few web-sites that occur to become detailed below, from our point of view are undoubtedly properly worth checking out.
Here is a good Blog You might Come across Intriguing that we encourage you to visit.
We prefer to honor numerous other world wide web web pages on the internet, even when they aren?t linked to us, by linking to them. Under are some webpages worth checking out.
We prefer to honor many other net web-sites around the net, even when they aren?t linked to us, by linking to them. Beneath are some webpages really worth checking out.
Usually posts some really interesting stuff like this. If you?re new to this site.
Just beneath, are several entirely not associated websites to ours, however, they’re certainly worth going over.
We came across a cool web site that you just could possibly appreciate. Take a appear for those who want.
One of our visitors not long ago recommended the following website.
Check below, are some totally unrelated internet websites to ours, nevertheless, they’re most trustworthy sources that we use.
Please stop by the web pages we follow, like this one, as it represents our picks from the web.
Wonderful story, reckoned we could combine a handful of unrelated information, nevertheless really really worth taking a appear, whoa did one particular study about Mid East has got much more problerms as well.
Although sites we backlink to beneath are considerably not connected to ours, we feel they’re in fact worth a go via, so have a look.
After all, what a great site and informative posts, I will upload inbound link – bookmark this web site? Regards, Reader.
Always a big fan of linking to bloggers that I enjoy but don?t get lots of link enjoy from.
Every as soon as inside a even though we decide on blogs that we study. Listed below would be the most current websites that we choose.
We prefer to honor several other net web-sites on the internet, even when they aren?t linked to us, by linking to them. Underneath are some webpages really worth checking out.
Check below, are some absolutely unrelated web sites to ours, even so, they may be most trustworthy sources that we use.
That may be the end of this post. Right here you will uncover some websites that we feel you?ll enjoy, just click the links.
Please pay a visit to the web pages we follow, like this a single, as it represents our picks in the web.
Here are some links to web-sites that we link to for the reason that we think they are really worth visiting.
Please check out the internet sites we stick to, like this one, because it represents our picks from the web.
Here are some hyperlinks to web-sites that we link to for the reason that we think they are worth visiting.
Para nosotros es de vital importancia que nuestros clientes queden completamente satisfechos, por lo que le ofrecemos un servicio técnico Bosch en Madrid impecable tanto insitu como por teléfono, y por supuesto garantía por escrito. Nuestros operarios cuentas con una amplia experiencia y se encuentran en formación continua para afrontar cualquier tipo de reparación en cualquier electrodoméstico Bosch en cualquier equipo de aire acondicionado Bosch. Gracias a nuestro equipo de profesionales, tanto administrativos como técnicos, se coordinará una visita a su domicilio el mismo día de su llamada.
Wonderful story, reckoned we could combine some unrelated data, nevertheless truly really worth taking a look, whoa did 1 find out about Mid East has got a lot more problerms also.
The information talked about inside the article are a few of the ideal available.
The information and facts mentioned within the write-up are several of the top available.
We came across a cool site that you simply might love. Take a look in the event you want.