开发者

Android: How to best pass data to a view?

开发者 https://www.devze.com 2023-02-09 01:58 出处:网络
I have a view that displays all the levels of my game. These levels are read by the activity and then passed into the view. I could read them from the view, but it\'s not really its responsibility, an

I have a view that displays all the levels of my game. These levels are read by the activity and then passed into the view. I could read them from the view, but it's not really its responsibility, and I'm a fan of separation of concerns.

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

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

However, I don't like the fact that the view will be dysfunctional i开发者_高级运维f I forget to call the setter. Is there a better way to pass the levels in?


It is also a bit a matter of preference. Theoretically it's perfectly fine to pass the levels as you're doing. Alternatively, if you need more than just set the levels, but provide further functionalities (i.e. also saving of levels) I normally use a separate class responsible for handling such things (i.e. a Repository, some "Manager" class etc...). This class is then passed into the View on the constructor preferably s.t. one is forced to provide it. Of course, in order to separate things, I use interfaces rather than specific implementations s.t. it may then look as follows:

public class MyView {

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

   ...
}

Often, this may not work, because the view is something instantiated by the framework directly rather than by the application. In such a situation you're forced to do it through an appropriate setter. It is some sort of MVC/MVP pattern.

Just for your interest, you might also want to take a look at IoC containers and dependency injection. Guice provided by Google is a nice framework I've already used on Android.


I hope I didn't miss the point, but here goes: Generally you have either a function setting something (like the text for a textview), or an attribute you set in the xml.

Take a look over at this answer I got on a question: How to layout a 'grid' of images in the center of the screen

There are some things the custom view needs, but lets take an example: 'numColumns'.

  • you can set it using setNumColumns (that would be the equivalent of your loadLevels() ? )
  • you can ignore it, it'll revert to default.
  • you can set it as an attribute lik so: app:numColumns="3"

You can try to use the attribute or the default in the class to accomplish this.


Make your view an abstract class with an abstract method getLevels()? This way, when you instantiate the class if you forget to pass the levels in your code won't compile.

Whether or not this is better is a matter of taste I guess :)

0

精彩评论

暂无评论...
验证码 换一张
取 消