Programming convention on Anonymous Class vs Implementing Interface - java

From the android development perspective, while you are programming which way do you prefer to implement for listener? Or which way do you think is the best for readable code? I gave two example about these things but think more complex classes such as which has more than one Listener:)
First example which is an Anonymous Class:
public class SenderReceiverActivity extends Activity {
Button cancelButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sending);
cancelButton = (Button) findViewById(R.id.button1);
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
}}
Second example which is implementing interface :
public class SenderReceiverActivity extends Activity implements OnClickListener {
Button cancelButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sending);
cancelButton = (Button) findViewById(R.id.button1);
cancelButton.setOnClickListener(this);
}
public void onClick(View v) {
}
}

if you have single button then first approch is right because there are no any complexity in your code but when you have many button then second is more clear ,just one onClick method for many buttons and check id of button using v.getId()
But there are no any change in functionality both are identical.

I think 2nd approch is good as
1- you can handle multiple Views click at one place...
2- it make code shorter and easy to read..
3- it is easy in maintenance.
4- if you are using the Base Activity like concept in your project then it is also useful.

Well, there isn't really much differences between both except one: in second case you have access to onClick(View v) method from outside the class.
If it comes to me I prefer first approach, because not often more than one component have at the same time the same behaviour on click.

Related

How was onClick(View v) Automatically executed?

Hi im a begginer on Android development. I knew basic core java. So i have a question on this particular code:
button.setOnClickListener(new View.OnClickListener()
{
#Override public void onClick(View v)
{
// do something when the button is clicked
}
});
I know that this is anonymous class and OnClickListener is an interface. But what i dont understand is the onClick(View v) method, v is the button that was clicked but under the hood how was this method AUTOMATICALLY executed? I mean isnt that to be able to call a method you must first create an object then a method beside it? I just need to understand this concept, thank you.
In simple words when you create a Button object it has some listener objects:
Example:
class Button extends View{
private OnClickListener clickListener;
public void setOnClickListener(OnClickListener clickListener){
this.clickListener = clickListener;
}
}
when you call this:
button.setOnClickListener();
basically you assign the value to clickListener in Button class and then each time you click the button it triggers
clickListener.onClick(this)
and perform your defined stuff.
Your listener is provided to the Button object, and by clicking the button, the Android framework will try to invoke the OnClickListener (if any) by calling the onClick method you provide.
So it is not really automatically. Your action triggers the click, and Android framework calls your onClick.

Best way to implement View.OnClickListener in Android

Suppose we have an Activity with a lot of views on which OnClickListener is to be registered.
The most common way to implement this is to let the Activity-Subclass implement the OnClickListener, something like this:
public class ActivityMain extends Activity implements View.OnClickListener
{
#Override
public void onClick(View view)
{
switch (view.getId())
{
//handle multiple view click events
}
}
}
The way I like to implement it is to create a private class inside the Activity-Subclass and let that inner class implement the OnClickListener:
public class ActivityMain extends Activity implements View.OnClickListener
{
private class ClickListener implements View.OnClickListener
{
#Override
public void onClick(View view)
{
switch (view.getId())
{
//handle multiple view click events
}
}
}
}
This way the code seems more organized and easy to maintain.
Moreover, talking about "Is-a", "Has-a" relationships, the latter seems to be a good practice because now the Activity-Subclass would have a "Has-a" relationship with the ClickListener.
While in the former method we would be saying that Our Activity-Subclass "Is-a" ClickListener, which ain't completely true.
Note that, I am not concerned with the memory overhead the latter would cause.
Also, adding onClick tag in xml is completely out of question.
So, what really is the best way to implement a ClickListener?
Please don't suggest any libraries like RoboGuice or ButterKnife etc.
UPDATE:
I would like to share the approach I finally adopted.
I directly implement the listener in Activity/Fragment.
As far as OOP design is concerned. The "HAS-A" approach doesn't offers any practical benefits and even takes up more memory. Considering the amount of nested classes (and the memory overhead) we will be creating for every similar listener we implement, this approach should clearly be avoided.
First, there is no best practice defined by Android regarding registering click listeners. It totally depends on your use case.
Implementing the View.OnClickListener interface to Activity is the way to go. As Android strongly recommends interface implementation over and over again whether it is an Activity or Fragment.
Now as you described :
public class ActivityMain extends Activity implements View.OnClickListener
{
private class ClickListener implements View.OnClickListener
{
#Override
public void onClick(View view)
{
switch (view.getId())
{
//handle multiple view click events
}
}
}
}
This is your approach. Now it is your way of implementation and there is nothing wrong with this if you are not concerned with memory overhead. But what's the benefit of creating the inner class and implementing the View.OnClickListener if you can simply implement that in the main class which can also lead to the code clarity and simplicity that you need.
So it just a discussion rather getting the best possible solution of implementing the View.OnClickListener because if you go with the practical point of everyone, you will go for a solution which is simple and memory efficient.
So I would prefer the conventional way. It keeps things simple and efficient. Check the code below:
#Override
public void onClick(View view)
{
switch (view.getId())
{
//handle multiple view click events
}
}
P.S : Your approach will definitely increase lines of code :P ;)
First of all lets get the basics clear here..
By implementing an Interface, your class doesn't become that.. like you said:
"Our Activity-Subclass "Is-a" ClickListener, which ain't completely true."
Your class can only have "Is-a" relationship if it extends, in this case an Activity. Implementing an interface means that it can behave like what interface has set its contract.
An Example:
class Peter extends Human .. means Peter is a Human..
class Peter can also implement programmer, musician, husband etc
means Peter can behave as the above.
As for best practice, you could make an entirely separate class which implements OnClickListener like this:
class MyListener implements View.OnClickListener{
#Override
public void onClick(View view) {
// do whatever you want here based on the view being passed
}
}
And in your main Activity you could instantiate MyListener and call onClick() and pass your view in it:
MyListener listener = new MyListener();
Button b = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
listener.onClick(button);
}
I use button.setOnClickListener(this); where my Activity implements View.OnClickListener, and then get the ID of the Button in a separate method. See below for an example:
public class MyActivity extends ActionBarActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YOUR_LAYOUT);
...
Button myFirstButton = (Button) findViewById(R.id.YOUR_FIRST_BUTTON);
myFirstButton.setOnClickListener(this);
Button mySecondButton = (Button) findViewById(R.id.YOUR_SECOND_BUTTON);
mySecondButton.setOnClickListener(this);
...
}
...
#Override
public void onClick(View v) {
Button b = (Button) v;
switch(b.getId()) {
case R.id.YOUR_FIRST_BUTTON:
// Do something
break;
case R.id.YOUR_SECOND_BUTTON:
// Do something
break;
...
}
}
...
}
Here you can create a btnClickListner object and after that you will call that btnCLickLisner object when ever you want to perform the onCLieck actions for buttons..
Let us assume, in my activity i have a 5 to 10 buttons and writing each button separate onclick listner is bad idea. So to over come this,we can use like below..
register your buttons
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
Button button3 = (Button)findViewById(R.id.button3);
Button button4 = (Button)findViewById(R.id.button4);
Button button5 = (Button)findViewById(R.id.button5);
Here i am setting the onclick listner to my buttons after click
button1.setOnClickListener(btnClickListner);
button2.setOnClickListener(btnClickListner);
button3.setOnClickListener(btnClickListner);
button4.setOnClickListener(btnClickListner);
button5.setOnClickListener(btnClickListner);
Here is the btnClick Listner implementation
View.OnClickListener btnClickListner = new OnClickListener()
{
#Override
public void onClick( View v )
{
// TODO Auto-generated method stub
if( button1.getId() == v.getId() )
{
//Do Button1 click operations here
}
else if( button2.getId() == v.getId() )
{
// Do Button2 click operations here
}
else if( button3.getId() == v.getId() )
{
// Do Button3 click operations here
}
else if( button4.getId() == v.getId() )
{
// Do Button4 click operations here
}
else if( button5.getId() == v.getId() )
{
// Do Button5 click operations here
}
}
}
I have found using Butterknife makes for clean code. And because it uses code generation (not reflections) it has little performance overhead.
public class ActivityMain extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
#OnClick(R.id.button_foo)
void onFoodClicked() {
// Do some foo
}
#OnClick(R.id.button_bar)
void onBarClicked() {
// do some bar
}
}
For this particular case I'd say that maintain a single instance of a OnClickListener is the best approach for you. You will have a "Has-a" relationship and won't need to create several instances since you are handling the behavior using the view id in the onClick(View view) callback.
public class ActivityMain extends Activity implements View.OnClickListener {
private View.OnClickListener mClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
//handle multiple view click events
}
}
};
}
Your ClickListener is an inner non-static class the coupling of this 'has-a' is no different than if your class Activity implemented View.OnClickListener. This is because your inner ClickListener requires an instance of ActivityMain and really can't be reused. I would argue that you're over engineering and aren't actually gaining anything.
EDIT: To answer your question I like to have anonymous View.OnClickListener for each widget. I think this creates the best separation of logic. I also have methods like setupHelloWorldTextView(TextView helloWorldTextView); where I put all my logic related to that widget.
First approach is better than the other because thats why View.OnClickListener is an Interface instead of an abstract class. besides the later might leak in various situations since you are using a non-static inner class.
A small remark to this, and maybe a little bit of topic.
What, if we not just implement OnClickListener and we have a bunch of other Listeners / Callback to implement. In my Opinion it will get messy to implement all of these in the class instead of using anonymous classes / lambda. It is hard to remember wich method belongs to which interface.
So if we have to implement an interface (in this case OnClickListener) multiple times it my be a good solution to implement on class base and use the switch/case.
But if we have to implement multiple interfaces it may be a good solution to use anonymous classes / lambda
simply you using like not implements subclass or not handle a click event just do like this way .
android.view.View.OnClickListener method_name = new android.view.View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// put your code .
}
};
and handle click event into button ya any type of click event like
button_name.setOnClickListener(method_name);
its work very simply
Thanks
public class ProfileDetail extends AppCompatActivity implements View.OnClickListener {
TextView tv_address, tv_plan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_detail);
tv_address = findViewById(R.id.tv_address);
tv_plan = findViewById(R.id.tv_plan);
tv_address.setOnClickListener(this);
tv_plan.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_plan:
startActivity(new Intent(getApplicationContext(),PlanActivity.class));
break;
case R.id.tv_address:
startActivity(new Intent(getApplicationContext(),AddressActivity.class));
break;
}
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Chronometer chronometer;
private Button startButton;
private Button stopButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chronometer = findViewById(R.id.chronometer);
startButton =findViewById(R.id.startBtn);
stopButton = findViewById(R.id.stopBtn);
startButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.startBtn:
chronometer.start();
break;
case R.id.stopBtn:`
chronometer.stop();
break;
}
}
}
It really depends on what you want to achieve. If you have e.g. a complex functionality with threading, dependencies, etc., I personally like to decouple it completely from the Activity into a separate class XyzAction, that does the heavy stuff, knows about certain Invokers and returns them results, if needed. My Invokers are basically objects, that implement OnClick/OnTouch/etc.Listeners and bind themselves to needed actions. E.g. there could be a LoginInvoker implementing OnClickListener for a Button and an ImageView and also a generic ActionListener that gets invoked when a MenuItem is clicked. The Invoker has update methods for showing progress to the user and the result of the bound action. The action posts updates to its Invokers and can be garbage collected, if all of them die, because it has no connection to the UI.
For less complex actions, I couple them directly to the Android component (i.e. Activity/Feagment/View) and also call them Actions, with the big difference of them implementing the UI callbacks directly.
In both cases I declare the actions as members, so I can see on a quick glance what specific actions the Android component supports.
If there's something trivial like "show a Toast if button is pressed", I use anonymous inner classes for the UI callbacks, because you normally don't care that much about them with regards to maintainability.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button north,south,east,west;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
north.setOnClickListener(this);
south.setOnClickListener(this);
east.setOnClickListener(this);
west.setOnClickListener(this);
}
private void init(){
north = findViewById(R.id.north);
south = findViewById(R.id.south);
east = findViewById(R.id.east);
west = findViewById(R.id.west);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.north:
Toast.makeText(MainActivity.this,"NORTH",Toast.LENGTH_SHORT).show();
break;
case R.id.south:
Toast.makeText(MainActivity.this,"SOUTH",Toast.LENGTH_SHORT).show();
break;
case R.id.east:
Toast.makeText(MainActivity.this,"EAST",Toast.LENGTH_SHORT).show();
break;
case R.id.west:
Toast.makeText(MainActivity.this,"WEST",Toast.LENGTH_SHORT).show();
break;
}
}
}

Using buttons on android - newbie

I am a newbie to android development, trying to get buttons working. every time i use this code below, the error message "unfortunately the app has stopped". but when i remove the code the app runs but obviously the buttons do nothing. here is the code ive tried
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.ExerciseButton);
button1.setOnClickListener (new View.OnClickListener(){
public void onClick(View v) {
setContentView(R.layout.exercises);
}
});
}
}
anybody able to help me out there? thanks
Don't try to load another View in the current activity. Navigate to a new ExercisesActivity.
Use:
public void onClick(View v) {
Intent intent = new Intent(ExercisesActivity.this, WcActivity.class);
startActivity(intent);
}
You can't call setContentView anymore after the view has loaded (which it obviously has to receive button clicks). Use a different approach, like showing and hiding views or using a ViewFlipper (see Calling setContentView() multiple times), using fragments (see Fragments) or starting a new activity.
Well, from your code, I see a couple of things:
I am usually familiar to using the onClickListener of the Button class if I want to use it for a button. Makes sense, doesn't it?
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do stuff here
}
Second thing:
Start a new Activity (if that is what you want) by using an Intent:
Intent myIntent = new Intent(this, exercises.class);
startActivity(myIntent);
You CAN absolutaly call setContentView on any event, even after the view has loaded
I tried your code in a demo project and it is working fine. So, i think the error will be some where in your layout.(Let me know more if you need more help on this)

Why OnClickListener interface is not implemented and passed as new in setOnClickListener() method?

I am learning JAVA for Android. I have read that Interfaces should be implemented. But i have confusion here:
final CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (checkbox.isChecked()) {
checkbox.setText("I'm checked");
} else {
checkbox.setText("I'm not checked");
}
}
});
we are passing and implementing OnClickListener interface directly here. What is exact reason for this? Please explain this concept in details.
It's because you want to implement it individually for each individual clickable widget. OnClickListener is an inner interface in the View class and logically it would not make sense to make the activity implement it as then any click on the screen even outside of this would trigger unexpected action.
Interfaces alone do not have an implementation. But here what you're actually doing is creating a new anonymous class (a class without a name) that implements the OnClickListener interface and defining the implementation of it all in one place.
As for why you would do this- for very small simple implementations it can be clean, and it prevents you from having dozens of little classes that implement 1 or 2 functions. If the implementation is long it can become difficult to read though. But its never wrong to do it the long way and use a regular class.
Normally we implement OnClickListener like below,
public class MainActivity extends Activity implement OnClickListerner
{
....
view.setOnClickListener(this); // When we are implemeting OnClickListener
#Override
public void onClick(View v)
{
....
}
}
When we implement OnClickListener in that case we set it using setOnClickListener(this), here this refers to OnClickListener listener.
However we can do same thing by declaring another way known as anonymous block as below,
CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (checkbox.isChecked()) {
checkbox.setText("I'm checked");
} else {
checkbox.setText("I'm not checked");
}
}
});

What's the effect of implementing the OnClickListener with an Activity?

I don't understand why I have to implement the OnClickListener to use the OnClick-method. Assuming this code:
public class KlickitestActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onClick(View v) {
// code what happens when a click is made
}
From the class OnClickListener I only use the method onClick(View v) - and this one is overwritten. Why can't I just define the onClick-method without implementing the OnClickListener?
You can. You can do that by using an Anonymous Inner Class :
Button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Do stuff
}});
Button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Do stuff
}});
However implementing an OnClickListener makes it easier to handle events, and improves code readability. i.e You can use one Listener method, and passing a View to handle multiple buttons/listeners with a switch statement, something similar to :
public void onClick(View view){
switch(view.getId()){
case R.id.Button1:
//Stuff for button 1
break;
case R.id.Button2:
//Stuff for button 2
break;
break;
case R.id.Button3:
//Stuff for button 3
break;
}
Just to expand on Mob's answer and also Scott's comment and link...
An Activity is primarily a framework for a UI and as such has no pre-defined way of interacting with a user. As designers / developers we choose which UI components we want the Activity to contain based on the purpose of the Activity.
The UI components such as Buttons, CheckBoxes, ListViews and so on, serve very different purposes and it is not the place of an Activity in it's basic form to know what events those UI elements react to (click, long-click, swipe etc) simply because there is no pre-defined set of UI elements that an Activity will always host. As such it is our responsibility to implement the event handlers (listeners) that we need to use based on how we design the UI.

Categories