Kotlin basics : RatingBar, listeners - kotlin

I started learning Kotlin few weeks ago and I need help understanding the basics.
What is a listener? For example, what is RatingBar's listener? How do I find a listener of other widgets?
What are the parameters? Again, what is RatingBar's parameters? How do I find the parameters of other widgets?
What is View.____?

If you're writing a component that handles events of some kind, you'll probably want a way to inform other components about those events. There are lots of ways to do this (in a software design sense), and one of those is the idea of a listener.
The basic idea is that components can register themselves as listeners, and when a relevant thing happens, they get a callback. The component generating the events doesn't need to know what those listeners are, it just needs to hold a reference to one (or more) and call some callback function when the event happens. The key thing here is that the component doesn't have a listener, you have to provide them. You're hooking components up.
So a typical way to do this is for a component to implement a callback interface, which basically says "I have a function called this with these parameters" and the event component can just call that function with the details when an event happens. You could also create an object that implements that interface, or in Kotlin's case you can just pass a function in that matches the signature of the callback function - basically providing a block of code that says "when the event happens, do this stuff in response". That's typically how you define behaviour, like setting an on-click listener - you write a block of code to execute when the user clicks a thing, and when the event happens, that code gets run.
I hope that makes sense generally - if any of it's confusing (since you're new) I'd recommend reading the basic trails in the Java Tutorials (which Kotlin is based on) to get a handle on interfaces and the like.
As for the other questions... if you're asking what the parameters are when you construct a RatingBar or whatever, the best place to look is the documentation (although you generally won't be constructing Views in code anyway, just adding them to a layout XML file) - Android Studio should pop up some hints too (you can hit ctrl+q for documentation on the thing your cursor is currently over, or ctrl+p for parameter hints).
If you're asking what a View is, it's the base class for Android's UI components, it's really anything that's able to draw itself and be included in a layout. It has a lot of methods because it has a lot of functionality built in to handle all these UI responsibilities.
If you're asking what View.something is, that's a static method or field defined on the View class - if you don't know what that means, read the Java tutorial link I included! You'll typically be referencing things like View.VISIBLE which is a set value you provide to a View's setVisibility method - it knows what those values mean and what to do with them

Related

What is the purpose of events in ABAP?

Learning ABAP from a book, I got to the object/class events. I know events from other languages (as C#/WinForms) as connection between user action in GUI (e.g. button click) and some piece of code executed after the interaction. There is also possibility to trigger such event from a code to simulate user action, which can be sometimes useful.
The book ends the example with RAISE EVENT statement triggering the event manually from the code. It is same in other sources online (e.g. 1, 2, 3, 4, 5). I don’t see any reason to raise event from code if I can call the object method directly. It seems like needless layer of code to me. What is the purpose or benefit of using events in ABAP? What do I miss?
Thank you for the comments; they got me on the right track. Problem with many sources is they show very simple example where events bring no benefit. It is same as using OOP for a few lines of code, or recursion instead of simple cycle. Such easy example is good to learn the syntax, but it is insufficient to understand the purpose or benefits.
Using events and handlers in one class doesn’t make much sense for me. Most of examples come with two classes (still putting together things that can be alone). For me, an example with three separate pieces of code brought the biggest benefit. According to my understanding, the key points are:
Class A has an event defined by command EVENTS. Class A needs no reference to other classes. In my words: Some situation interesting for the others can happen inside. The class has no knowledge of the outside world (no dependency), but it can signal to the world that the situation happened.
Only the object A can raise (fire, trigger) the event from its inside code by command RAISE EVENT. In my words: It is broadcasted outside (to anyone who could concern and subscribes) that the situation happened.
Class B defines method/handler for the class A by command METHODS - FOR EVENT – OF that CAN be used to handle the event. This class needs to know class A and its event. In my words: Class B offers code to handle situation that can occur in class A.
Some third piece of code having knowledge of both classes (probably creating them) says: when the event in class A raises use this handler by command SET HANDLER - FOR. Most importantly, it can be also another handler from different class than B. In my words: When using class A, I can easily set what will happen after the situation in A by selecting from a range of suitable handlers that A doesn’t know.
Because I miss a good example, here is a demonstration of the points:
CLASS lcl_class_a DEFINITION.
PUBLIC SECTION.
DATA a1 TYPE I.
EVENTS: my_event.
METHODS: method_raising_event.
ENDCLASS.
CLASS lcl_class_a IMPLEMENTATION.
METHOD method_raising_event.
"some working code would be here
RAISE EVENT my_event.
ENDMETHOD.
ENDCLASS.
CLASS lcl_class_b DEFINITION.
PUBLIC SECTION.
"This methods could be run after the event.
METHODS: handle_event1 FOR EVENT my_event OF lcl_class_a,
handle_event2 FOR EVENT my_event OF lcl_class_a.
ENDCLASS.
CLASS lcl_class_b IMPLEMENTATION.
METHOD handle_event1.
WRITE: / 'Event in class raised'.
ENDMETHOD.
METHOD handle_event2.
" Some code, e.g. logging to a file.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA(object_a) = new lcl_class_a( ).
DATA(object_b) = new lcl_class_b( ).
"Binding event and handler.
SET HANDLER object_b->handle_event1 FOR object_a.
CALL METHOD object_a->method_raising_event.
Additions:
In real life scenarios, it is useful to have reference to object of class A (raiser) in the object of class B (handler). You may need to get an additional information about the event from class A. But it is not necessary.
More handlers can be attached to one event.
The purpose or benefits are much clearer when aware of some design patterns. Some were mentioned in benefits. I would go with this hierarchy from general to particular:
SOLID
Loose coupling / Decoupling / Separation of concerns
Dependency inversion principle
Observer – Observable / Subscriber – Publisher
Happy to read comments on my answer.

Data binding without a ViewModel

I am doing something I have never tried before. I am trying to create dynamic UI and bind it to a dynamic model. In other words, my web service is going to send back a small metadata description of my UI and the raw data to bind to it. Therefore, at build time, I don't know what UI I will be constructing and I don't know what my model will be. Binding them together seems VERY difficult if not impossible.
Mvx allows me to bind UI directly to a model WITHOUT it being an MvxViewModel. However, if I bind directly to the Model returned by the web service, I lose the ability to RaisePropertyChanged() since that only comes from MvxViewModel.
Normally, I would write a ViewModel that wraps the Model and have all the wrapped setters call RaisePropertyChanged(). However, in this case, my model is dynamic so I can't wrap it with a ViewModel at compile time since I don't know what it is until runtime.
Is there some cool trick I can use to construct a ViewModel that can wrap any C# model class and send out property changed events without knowing what properties the model class has until runtime?
I just discovered the DLR and the DynamicObject which seems to be perfect, but due to Apple restrictions, it will not work on Xamarin.iOS.
Without teasing DynamicObject into life on iOS, the main approaches that think of are:
You could change your webservice generation code so that it produces INotifyPropertyChanged - I've used libraries that do this - e.g. http://stacky.codeplex.com/SourceControl/latest#trunk/source/Stacky/Entities/Answer.cs - and if you can't change the webservice code generation itself, you might still be able to wrap or pervert the generated code using some kind of t4 or other templating trick.
You could investigate some kind of code that maps the web service objects to some kind of observable collection (Kiliman has suggested this in comments)
You could look at some kind of valueconverter (or maybe valuecombiner) which does the binding - I can fairly easily imagine a valueconverter which takes a wrapped model object and a string parameter (the property name) and which uses those two together (with some reflection) to work out what to do. I'm not as sure how this one would work with nested model objects... but even that could be possible...
You could look at some kind of custom binding extension for MvvmCross. This isn't as scary as it sounds, but does require some reflection trickery - to understand what might be involved take a look at the FieldBinding plugin - https://github.com/MvvmCross/MvvmCross-Plugins/tree/master/FieldBinding
During the actual data-binding process, the plugin will be called via IMvxSourceBindingFactoryExtension - that would be your opportunity to hook into some other custom change event (rather than INotifyPropertyChanged). It might take a little experimentation to get this right... especially if you have nested objects (which then require "chaining" within the binding)... but I think it should be possible to produce something this way.
I am not sure if what I finalized on supports all possible functionality, but so far, it seems to satisfy everything that I need.
I really liked the idea of writing my own IMvxSourceBindingFactoryExtension. However, in investigating how to do that, I started playing with the functionality that already exists within MvvmCross. I already knew that MvvmCross would honor an ObservableCollection. What I didn't know was that I could use [] in my binding expressions AND that not only would integer indexers work, but also string indexers on a Dictionary. I discovered that MvvmCross sample code already has an implementation of ObservableDictionary within its GIT repo. It turns out, that is all that I needed to solve my problem.
So my model contains static properties AND an ObservableDictionary<string,object> of dynamic properties where the key is the name of the dynamic property and the value is the value of the property.
My ViewModel wraps this model class to send out PropertyChanged notifications on the static properties. Since the Dictionary of dynamic properties is observable, MvvmCross already handles changes to members of that dictionary, including 2-way.
The final issue is how to bind to it in my binding expression. That is where the [] comes in. If my ObservableDictionary property name is called UserValues and it contains a value at key user1, then I can 2-way bind to it by using: UserValues[user1] and everything seems to work perfectly.
One issue I see is that I am now requiring my dynamic data source to return an ObservableDictionary to me instead of just a Dictionary. Is that asking too much?

What are Smalltalk pragmas conceptually?

I have used pragmas in Pharo Smalltalk and have an idea about how they work and have seen examples for what they are used in Pharo.
My questions are:
what are pragmas conceptually,
to what construct do they compare in other languages,
when should i introduce a pragma?
I already found an interesting article about their history: The history of VW Pragmas.
You must think of it as Annotations attached to a CompiledMethod, or if you want as additionnal properties.
Then, thanks to reflection, some tools can walk other compiled methods, collect those with certain annotations (properties) and apply some special handling, like constructing a menu, a list of preferences, or other UI, invoking every class methods marked as #initializer, or some mechanism could be walking the stack back until a method is marked as an #exceptionHandler ...
There are many possibilities, up to you to invent your own meta-property...
EDIT
For the second point, I don't know, it must be a language that can enumerate the methods, and can attach properties to them.
The third point is also hard to answer. In practice, I would say you would use some already existing annotations, but very rarely create a new one, unless you're trying to create a new framework for exception handling, or a new framework for GUI (you want to register some known events or some handlers...). The main usage I would see is for extending, composing an application with unrelated parts, like a main menu. It seems like a relatively un-intrusive way to introduce DECLARATIVE hooks - compared to the very intrusive way to override a well known method TheWorld>>mainMenu. It's also a bit lighter than registering/un-registering IMPERATIVELY via traditional message send at class initialization/unoading. On the other hand, the magic is a bit more hidden.

Communication in component-based game engine

For a 2D game I'm making (for Android) I'm using a component-based system where a GameObject holds several GameComponent objects. GameComponents can be things such as input components, rendering components, bullet emitting components, and so on. Currently, GameComponents have a reference to the object that owns them and can modify it, but the GameObject itself just has a list of components and it doesn't care what the components are as long as they can be updated when the object is updated.
Sometimes a component has some information which the GameObject needs to know. For example, for collision detection a GameObject registers itself with the collision detection subsystem to be notified when it collides with another object. The collision detection subsystem needs to know the object's bounding box. I store x and y in the object directly (because it is used by several components), but width and height are only known to the rendering component which holds the object's bitmap. I would like to have a method getBoundingBox or getWidth in the GameObject that gets that information. Or in general, I want to send some information from a component to the object. However, in my current design the GameObject doesn't know what specific components it has in the list.
I can think of several ways to solve this problem:
Instead of having a completely generic list of components, I can let the GameObject have specific field for some of the important components. For example, it can have a member variable called renderingComponent; whenever I need to get the width of the object I just use renderingComponent.getWidth(). This solution still allows for generic list of components but it treats some of them differently, and I'm afraid I'll end up having several exceptional fields as more components need to be queried. Some objects don't even have rendering components.
Have the required information as members of the GameObject but allow the components to update it. So an object has a width and a height which are 0 or -1 by default, but a rendering component can set them to the correct values in its update loop. This feels like a hack and I might end up pushing many things to the GameObject class for convenience even if not all objects need them.
Have components implement an interface that indicates what type of information they can be queried for. For example, a rendering component would implement the HasSize interface which includes methods such as getWidth and getHeight. When the GameObject needs the width, it loops over its components checking if they implement the HasSize interface (using the instanceof keyword in Java, or is in C#). This seems like a more generic solution, one disadvantage is that searching for the component might take some time (but then, most objects have 3 or 4 components only).
This question isn't about a specific problem. It comes up often in my design and I was wondering what's the best way to handle it. Performance is somewhat important since this is a game, but the number of components per object is generally small (the maximum is 8).
The short version
In a component based system for a game, what is the best way to pass information from the components to the object while keeping the design generic?
We get variations on this question three or four times a week on GameDev.net (where the gameobject is typically called an 'entity') and so far there's no consensus on the best approach. Several different approaches have been shown to be workable however so I wouldn't worry about it too much.
However, usually the problems regard communicating between components. Rarely do people worry about getting information from a component to the entity - if an entity knows what information it needs, then presumably it knows exactly what type of component it needs to access and which property or method it needs to call on that component to get the data. if you need to be reactive rather than active, then register callbacks or have an observer pattern set up with the components to let the entity know when something in the component has changed, and read the value at that point.
Completely generic components are largely useless: they need to provide some sort of known interface otherwise there's little point them existing. Otherwise you may as well just have a large associative array of untyped values and be done with it. In Java, Python, C#, and other slightly-higher-level languages than C++ you can use reflection to give you a more generic way of using specific subclasses without having to encode type and interface information into the components themselves.
As for communication:
Some people are making assumptions that an entity will always contain a known set of component types (where each instance is one of several possible subclasses) and therefore can just grab a direct reference to the other component and read/write via its public interface.
Some people are using publish/subscribe, signals/slots, etc., to create arbitrary connections between components. This seems a bit more flexible but ultimately you still need something with knowledge of these implicit dependencies. (And if this is known at compile time, why not just use the previous approach?)
Or, you can put all shared data in the entity itself and use that as a shared communication area (tenuously related to the blackboard system in AI) that each of the components can read and write to. This usually requires some robustness in the face of certain properties not existing when you expected them to. It also doesn't lend itself to parallelism, although I doubt that's a massive concern on a small embedded system...?
Finally, some people have systems where the entity doesn't exist at all. The components live within their subsystems and the only notion of an entity is an ID value in certain components - if a Rendering component (within the Rendering system) and a Player component (within the Players system) have the same ID, then you can assume the former handles the drawing of the latter. But there isn't any single object that aggregates either of those components.
Like others have said, there's no always right answer here. Different games will lend themselves towards different solutions. If you're building a big complex game with lots of different kinds of entities, a more decoupled generic architecture with some kind of abstract messaging between components may be worth the effort for the maintainability you get. For a simpler game with similar entities, it may make the most sense to just push all of that state up into GameObject.
For your specific scenario where you need to store the bounding box somewhere and only the collision component cares about it, I would:
Store it in the collision component itself.
Make the collision detection code work with the components directly.
So, instead of having the collision engine iterate through a collection of GameObjects to resolve the interaction, have it iterate directly through a collection of CollisionComponents. Once a collision has occurred, it will be up to the component to push that up to its parent GameObject.
This gives you a couple of benefits:
Leaves collision-specific state out of GameObject.
Spares you from iterating over GameObjects that don't have collision components. (If you have a lot of non-interactive objects like visual effects and decoration, this can save a decent number of cycles.)
Spares you from burning cycles walking between the object and its component. If you iterate through the objects then do getCollisionComponent() on each one, that pointer-following can cause a cache miss. Doing that for every frame for every object can burn a lot of CPU.
If you're interested I have more on this pattern here, although it looks like you already understand most of what's in that chapter.
Use an "event bus". (note that you probably can't use the code as is but it should give you the basic idea).
Basically, create a central resource where every object can register itself as a listener and say "If X happens, I want to know". When something happens in the game, the responsible object can simply send an event X to the event bus and all interesting parties will notice.
[EDIT] For a more detailed discussion, see message passing (thanks to snk_kid for pointing this out).
One approach is to initialize a container of components. Each component can provide a service and may also require services from other components. Depending on your programming language and environment you have to come up with a method for providing this information.
In its simplest form you have one-to-one connections between components, but you will also need one-to-many connections. E.g. the CollectionDetector will have a list of components implementing IBoundingBox.
During initialization the container will wire up connections between components, and during run-time there will be no additional cost.
This is close to you solution 3), expect the connections between components are wired only once and are not checked at every iteration of the game loop.
The Managed Extensibility Framework for .NET is a nice solution to this problem. I realize that you intend to develop on Android, but you may still get some inspiration from this framework.

Pass or Get a value from Parent ViewModel down to Sub-ViewModel?

I am using the MVVM Light framework as well as Unity for DI. I have some nested Views, each bound to a corresponding ViewModel. The ViewModels are bound to each View's root control DataContext via the ViewModelLocator idea that Laurent Bugnion has put into MVVM Light. This allows for finding ViewModels via a static resource and for controlling the lifetime of ViewModels via a Dependency Injection framework, in this case Unity. It also allows for Expression Blend to see everything in regard to ViewModels and how to bind them.
As I stated the Views have a healthy dose of nesting, but the ViewModels don't really know anything about each other. A parent view binds to its corresponding ViewModel via the static resource ViewModelLocator (which uses Unity to control the construction and lifetime of the ViewModel object). That parent view contains a user control in it that is another sub-view, which then goes and gets its corresponding ViewModel via the ViewModelLocator as well. The ViewModels don't have references to each other or know any hierarchy in regard to each other.
So here's an example of how the ViewModels do interact via messaging. I've got a parent View that has a ComboBox databound to an ObservableCollection in its ViewModel. The ComboBox's SelectedItem is also bound (two-way) to a property on the ViewModel. When the selection of the ComboBox changes, this is to trigger updates in other Views and sub-Views. Currently I am accomplishing this via the Messaging system that is found in MVVM Light.
So I'm wondering what the best practice would be to get information from one ViewModel to another? In this case, what I need to pass down to sub-ViewModels is basically a user Guid representing the currently logged in user. The top-most parent View (well, ViewModel) will know this information, but I'm not sure how to get it down into the sub-ViewModels.
Some possible approaches I can think of:
Should the sub-ViewModel ask the
static resource ViewModelLocator for
a reference to the same object the
parent View is using and access the
property that way? It seems like
ViewModels going through each other's
properties is not very clean and
couples them together unnecessarily.
I'm already using messaging to notify
the sub-Views that the user selected
a new item in the ComboBox and to
update accordingly. But the object
type that is being selected in the
ComboBox is not really directly
related to this data value that the
sub-Views need.
I have seen basically two approaches to this. For general cross-VM communication the event aggregator pattern works great.
For hierarchies of VMs however using a Visitor pattern may be better. With a visitor you can have information that flows through the hierarchy for example giving each child a reference to the parent VM automatically.
You can also do this with EA, but the challenge is around passing enough information in the payload of the message such that the children know it's something they should care about.
As far as VM locator, absolutely not! The VM locator stuff is stricly for binding in the UI it should not surface itself outside of that context (optimally).
My $.02
Glenn
I decided to have the sub-ViewModels publish a message requesting the needed information and then have the parent VM subscribe to that message type and key token. I don't want to overuse this communication means, but I think it will be effective for a few pieces of data that I'm having trouble finding ways to push down through the View hierarchy. Up to this point, most of the data passing has all been in response to events, but not every piece of data can be passed around in this way, especially if the data is acquired or the event happens on a different screen before the new view is even constructed and read to receive the data.
I did have a twitter conversation with some well known names in this space (Glenn Block, John Papa, and Rob Eisenberg). They suggested a number of things like a Visitor Pattern, but I wasn't sure that would work so well without a hierarchy of VMs. This could be because my design has pretty much been View-first, as opposed to a ViewModel-first approach. Another suggestion which may have been workable would be to modify my ViewModelLocator and Dependency Injection use to include the ability to pass in the data values to the sub-VMs at creation time. I had a little trouble envisioning it because of the static nature of the VML, and decided the message request solution I came up with would be more straight forward and simple for the time being. I will likely have to rethink the solution if there ends up being too many more pieces of data falling into this situation.