Android: what is the best way to pass data to a view?

I have a view that displays all the levels of my game. These levels are read by activity and then passed to the view. I could read them from the point of view, but in fact it is not his responsibility, and I am a fan of sharing problems.

Right now, I'm calling the setter for this:

((GameView) findViewById(R.id.game)).setLevels(loadLevels()); 

However, I do not like the fact that the view will be dysfunctional if I forget to name the setter. Is there a better way to pass levels?

+4
source share
3 answers

This is also a little preferable. Theoretically, it’s great to go through the levels as you do. Alternatively, if you need more than just setting levels, but providing additional functions (for example, saving levels), I usually use a separate class responsible for handling such things (for example, a repository, some class β€œManager”, etc. .). This class is then passed to the view on the constructor, preferably st alone is forced to provide it. Of course, to separate things, I use interfaces, and not specific implementations of st, it can look like this:

 public class MyView { public MyView(ILevelLoader levelLoader){ this.levelLoader = levelLoader; } ... } 

Often this may not work, because a view is something created by the framework directly and not by the application. In such a situation, you are forced to do this through a suitable setter. This is a kind of MVC / MVP pattern.

Just for your interest, you can also take a look at IoC containers and dependency injection. Guice , provided by Google, is a good infrastructure that I have already used on Android.

+2
source

I hope I did not miss the moment, but here it goes: As a rule, you have either a function that sets something (for example, text for text), or an attribute set in xml.

Take a look at this answer, I asked a question: How to place an image grid in the center of the screen

There are some things in the user view, but let's take an example: 'numColumns'.

  • you can set it using setNumColumns (will it be the equivalent of your loadLevels ()?)
  • you can ignore it, it will return to default.
  • you can set it as a lik attribute like this: app:numColumns="3"

You can try using this attribute or the default value for this class.

0
source

Make your view an abstract class with the abstract getLevels() method? Thus, when you create an instance of a class, if you forget to go through the levels in your code, it will not compile.

Is it better, it is a matter of taste, I think :)

0
source

Source: https://habr.com/ru/post/1338641/


All Articles