Java "external on event call" - java

I am new to Java and I started to learn it on Android platform, I know its not good to start learning language on emulation of mobile platform, but anyway....
What I woud like to ask about java, is "external" calling of some methods. I mean, often in program, or tutorials, you just ovveride some method, and it gets run autmatically based on some action.
This is very nice actually, I really like it, but I would like to know how this this implemented. Does JVM has to implement those, or are they user-defineable somehow?
For axample on Android are methods surfaceCreated(),surfaceDestroyed() which are called on respective event, and you than can handle it. The similiar are button click handling, and many more events.
I would just like to know how this is implemented, becouse, for example in C you have to manually check wheather some action happened or not. And you are limited by data provided by OS. So, does JVM has predefined actions it can call, or can you manually somehow tell it to do somthing based on somthing? I know this is strange question, but in fact its so strange to me I cannot explain it better. Maybe you can understand my not-knowing if you knew I programmed mainly for MCU in C, so this behavior is strange to me. But I like it.

This is called Event-Delegation Model.
On occurrence of any event if listeners are registered, Proper delegates are called.
keep in mind that thing everything is oops in this and will be dealt in terms of classes and objects
We can understand this from a very simple Example say of a button click.
Consider i make this class
class MyButtonClickListener implements OnClickListener
{
public void onClick(View v)
{
//do something on button click
}
}
Now see this class is implementing a interface. This class has to provide body to the empty method of interface to implement it. else the code will not compile.
This ensures that every object of this class has a body of onClick Method. Now let us register this to listen our button click.
say my Button is button01
button01.setOnClickListener(new MyButtonClickListener());
now consider object button01 has a list maintained in it somewhere which has a address of object to do something later( new MyButtonClickListener() in our case).
now the layout managers are coded in a way that on a occurrence of a event (say button click) send this event to the object listener list to perform further action.
this will be happened in the fashion say when button is clicked then buttons list of listener is checked if it is found not null that means there is a listener. now on the reference found in the list , onClick Method is called. specifically onClick is called because we called the setOnCLickListener to set the listener. if you will check the code for this method. you will found method is receiving OnClickListener reference. this is a object of a class that implements the OnClickListener interface so must have provided a body to onClick method.
and thus this delegation is performed. this is simply oops. i hope i am able to explain it to a good level.

you ask about two distinct things:
some methods that you can override, which are called when some action happens (onResume(),...). They are always called (by the runtime/framework), and when your class overrides them, your implementation of that methods is called. But somewhere in the code is an actual call to this method. These are called virtual methods.
In the button click events you subscribe to are similar, but that is event-driven programming. When you subscribe to a button click event, for example
foo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
... do stuff
}
}
the foo object saves the OnClickListener somewhere to its internals. When the button is clicked, it looks in its internals if it has any OnClickListeners saved, and if so, it invokes onClick() method in each of them.

Related

Relation between android:onClick and View.OnClickListener s

Dabbling with Android Studio, and working through a few tutorials , but I don't understand a concept. Oh, and new to java too...haha.
Lets say I have a screen, an activity, MainActivity.xml with a button.
MainActivity.xml has an onClick attribute goForIt defined for the button.
In the MainActivity class I have a method goForIt.
This is where the button being clicked will be responded to.
Inside that goForIt method,
I build an Intent to start another activity,
and fire it off by the statement startActivity(intent)
Questions:
Why do I need a listener? (If I do)? The MainActivity.xml is an explicit directive to a specific method. Or is that a "listener"?
What's the role of the manifest in this? The activity is there... but for what purpose? Again, being able to find the class and method is pretty explicit without any need to consult a lookup like the manifest....?
I'm confused by the Activity XML having an explicit attribute to a specific method in the class, and then at the same time, the Listener saying that if the onClick happens, then do something... they are both trying to do the same thing are they not?
You can use listener or you can specify a method in xml to listen to the click on a view. In both you can the view as the parameter.
2.Manifest file helps you for many purpose:
to specify which activity is to be launched first
to get permissions for accessing internet, getting cal logs, using maps etc,
Specifying the theme or label for each activity and so and so ..
3.Both does the same thing. One is an alternative for other.
This question is waaay to wide and should be (probably will be) closed.
But, here goes:
onClick attribute in xml file is a shortcut for creating a listener (the listener in such case gets created behind your back). You either use that, or a listener done by hand.
Manifest has no role in this (pressing the button). But it is necessary to configure the activity so that it starts when the launcher icon is pressed (among many other things).
Android API looks as if it was never properly designed... it just grew and evolved. So yes, there are multiple, confusing ways to do a single thing.
Using
<Button
android:id="#+id/button"
android:onClick="goForIt"/>
and then
public void goForIt(View v) {
startActivity(...)
}
is exactly the same thing that using:
Button b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(...)
}
});
The first option is just a workaround, a short path to have the same effect.
Internally, it is just doing things the second way - take the button, add a click listener to it, and run it as soon as the user clicks on the button.
When your layout is inflated (after you call setContentView(R.layout.my_layout)) the attribute android:onClick gets internally converted into something like this:
Button b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goForIt(v);
}
});
The only difference is that it does it for you.
The manifest has no role in this context.
Why do I need a listener? (If I do)? The MainActivity.xml is an explicit directive to a specific method. Or is that a "listener"?
Think you have 10 buttons where click is required, so Listener can handle all those types of button click.
What's the role of the manifest in this? The activity is there... but for what purpose? Again, being able to find the class and method is pretty explicit without any need to consult a lookup like the manifest....?
From manifest Android ( application manager ) understands things about your app like, which page is 1st or launcher page.
I'm confused by the Activity XML having an explicit attribute to a specific method in the class, and then at the same time, the Listener saying that if the onClick happens, then do something... they are both trying to do the same thing are they not?
yes they are doing same thing, try to use listener for them.

SWT how to access efficiently other controls from SelectionListener

I have a swt button on ViewPart with attached MySelectionListener implements SelectionListener
There is also another button which is disabled.
Listener should do its work, if the return result of the work is true, it should enable the other button.
My question what would be the best way to do that?
For now what I do is to pass the button as constructor argument to 'MySelectionListener', I guess there is some other way to do it.
Another option is to to create an interface
public interface EnableButton(){
void enableButton();
}
And have the View implement it, then pass the interface to 'MySelectionListener' as constructor parameter once again...
I also don't like this approach, because this will require to create and implement multiple interfaces for each update or any other task that I would need.
I am not using any injection frameworks
Since your selectionListener seems to be only relevant for your ViewPart, you can implement it as an inner class inside your ViewPart.
Or you pass your ViewPart as constructor argument to MySelectionListener. Then let the method MySelectionListener.widgetSelected delegate to a method of ViewPart, where you have access to all the stuff you need, for example the button.

Getting a view's listener

Is it possible to get the listener that is attached to a view if it exists ? for example if i have a view i would like to get the listener that is listening to that view if there exists one
The only method I could find is View.getOnFocusChangeListener(). So a standard-library View will only tell you about its OnFocusChangeListener; for other listeners, no such getters are part of the class, so if you want to introduce those, you may have to subclass View.
Also, there are some methods that tell you whether a specific type of listener is attached to the View without returning the listener, for example whether a drag event listener, an on click listener or an on long click listener is attached to the View. Note: some of these methods may have side effects, check the docs on that.
No, if you take the OnClickListener for instance, it has protected access in View. Only a subclass could grant public access to the Listener fields, but no framework class does. On the other hand, you have the full responsibility to set the Listener in the first place, so you can set up your own data structures to track that information, if necessary.

Triggering a method from one class to an other using a button in Android SDK

I'm sorry if this is asked too much but I couldn't find something clear enough.
I'm developing a little game engine for android.
I've already implemented a gamepad class to control the touch screen.
The game pad class draws an analog stick if someone touches the right area and also draws to buttons on the side.
The problem is , making it simple, i have the main class GAME that as the LEVEL class and GAMEPAD class.
Inside the GAMEPAD code i can trigger things when someone pressed\releases a button.
The problem is I wan't to trigger something to the main GAME class by pushing a button witch is handled in the GAMEPAD class.
In C# i would use events and delegated.
In Java i have no clue.. i want the gpad to invoke a method to who is registered.
This is what i'm hoping to achieve on the main GAME class.
.. void onGpadClick (e EventArgument)
{
if (e.Button==Button.A&&e.ButtonState==ButtonState.Pressed) Shoot();
}
Thanks in advance
You can achieve this using Intents.
http://www.vogella.de/articles/AndroidIntent/article.html
What you could do is this:
Let your GAMEPAD-class recieve an instance GAME-class (either in its constructor or by a set-method)
In your GAME-class, you add methods containing what ever you want done for each button e.g. onButtonAClicked(), onButtonBClicked() and onPadClicked(). (If those are the options - add more if you have more options).
Detect the clicks from your GAMEPAD-class by setting a OnClickListener on each button e.g. buttonA.setOnClicklistner( new OnClickListener() { //override the onClick-method here } ) Then override the onClick-method and add your implementation there e.g. myGame.onButtonAClicked().
Hope it helps.

Java - Why do component functions call actionPerformed?

In my code, two comboboxes are added to actionListener( this );
In another part of my code, I call a combobox function that sets an index to a certain value. This in turn calls actionPerfoemed again and so getSource == comboBox is true. Every time I call a set function it calls actionPerformed again, creating a stack of function calls that then unwinds down to the first.
Is there a way to prevent this?
If the problem is just the initial setting, you can defer adding the listener until after both have been initialized. There's more discussion here.
From the Swing tutorial,
Combo boxes also generate item events, which are fired when any of the items' selection state changes.
These events will be generated either when a user clicks on the items with the mouse, or when your software calls setSelectedIndex().
Perhaps you don't want your actionPerformed() method in this to be called when your software calls setSelectedIndex(). You may need a Boolean eventInitiatedBySoftware. In your main (this) class, you could say
synchronized(eventInitiatedBySoftware) {
eventInitiatedBySoftware=true;
comboboxeditor.setSelectedIndex(n);
}
and then in your listener:
public void actionPerformed(ActionEvent ae) {
synchronized(eventInitiatedBySoftware) {
if (eventInitiatedBySoftware) {
eventInitiatedBySoftware=false; // clear your flag.
return; // don't want to process this event.
}
// the rest of your method goes here
}
When your software wants to adjust the value, it will set the Boolean to true. The actionPerformed method will be called, but your test will realise that this event was initiated by the software, and return before doing any of your existing code. It will clear the Boolean, so that if a user now uses the mouse to perform a selection action, your code will realise that it wasn't softwareInitiated.
BTW, It's possible that you misunderstand the event concept. For example, I suspect you are actually adding "this" as an event listener for each combobox, rather than adding comboboxes as listeners to "this". You might like to look at the Writing Event Listeners trail.

Categories

Resources