I am trying to make a View class that provides a Horizontal or Vertical layout depending on how it is created. I'm using a delegate to achieve this.
class View extends Manager {
private Manager mDelegate;
public View(Manager inDelegate) {
mDelegate = inDelegate;
// the delegate is the only child of "this" manager.
super.add(mDelegate);
}
public void add(Field f) {
// all other children go into the delegate.
mDelegate.add(f);
}
// other methods that also delegate
}
When I instantiate a View object I pass in a Horizontal or Vertical field manager and then delegate calls to that. This is kinda what the Screen class does in blackberry.
Actually I am looking at the blackberry docs for Screen to see what calls it delegates (so I can emulate that) and I notice calls like this in Screen...
protected boolean keyChar(char c, int status, int time)
Delegates key generation event to the controlled field with focus.
This method invokes Manager.keyChar(char, int, int) on this screen's delegate manager.
So then it immediately dawns on me, how in the world are they calling a protected method on the screen's delegate? Or are the docs wrong and this method isn't delegated?
Anyone know how they accomplish this?
Reminding myself what protected means:
A protected method can be called by
any subclass within its class, but not
by unrelated classes.
This doesn't directly answer your question, but could you extend Screen (API here) instead of Manager and then call super(mDelegate) in your constructor? Then presumably whatever magic is necessary will just work?
Aside from that I would just suggest you try it and see if you can override the supposedly protected method!
I managed to work out a solution to this problem with help from some other SO questions.
My solution is to create an interface that provides the public access points for the protected methods and then subclass the Manager class and mix in that interface. The public method will then call its super's protected method.
Then the View class is then passed one of these Manager subclasses.
public interface ManagerDelegate {
Manager asManager();
// Provide public access points to any protected methods needed.
void doProtectedMethod();
}
public HorizontalDelegate extends HorizontalFieldManager implements ManagerDelegate {
public Manager asManager() {
return this;
}
public void doProtectedMethod() {
// call the Manager's protected method.
protectedMethod();
}
}
public VerticalDelegate extends VerticalFieldManager implements ManagerDelegate {
public Manager asManager() {
return this;
}
public void doProtectedMethod() {
// call the Manager's protected method.
protectedMethod();
}
}
public class View extends Manager {
private final ManagerDelegate mDelegate;
public View(ManagerDelegate inDelegate) {
mDelegate = inDelegate;
}
protected void protectedMethod() {
// Call into our delegate's public method to access its protected method.
mDelegate.doProtectedMethod();
}
public void publicMethod() {
// For public delegated methods I can just get the Manager instance from
// the delegate and call directly.
mDelegate.asManager().publicMethod();
}
}
Related
I have inherited my view model class from INavigateAware interface as below,
public class ViewModel : INavigationAware
{
public ViewModel()
{
}
public void OnNavigatedFrom(NavigationParameters parameters)
{
}
public void OnNavigatedTo(NavigationParameters parameters)
{
// some codes
}
}
And called that view model in the associated view(the page I have been navigated to)
public partial class Page1 : ContentPage
{
ViewModel viewModel;
public Page1()
{
InitializeComponent();
viewModel = new ViewModel();
this.Content = myview; //myview is my control like grid
}
}
Now my problem is when I navigate to this page(Page1), OnNavigateTo() method in ViewModel is not triggered. Please someone helps me how to make trigger OnNavigateTo() method.
Thanks in advance.
First thing first, check if you have AutowireViewModel parameter in your page class set to True.
Second, you should not assign view model yourself, prism will do that for you, when you call PushViewModel
Third there is well known limitation in prism:
https://github.com/PrismLibrary/Prism/issues/563
There is also workaround suggested:
Create interface:
public interface IPageNavigationAware
{
void OnAppearing();
void OnDisappearing();
}
Derive your ViewModel class from this interface.
In the Views code behind:
protected override void OnAppearing()
{
(BindingContext as IPageNavigationAware)?.OnAppearing();
}
protected override void OnDisappearing()
{
(BindingContext as IPageNavigationAware)?.OnDisappearing();
}
The problem with that is that OnAppearing/OnDissapparing are not reliable navigation methods and do not accept parameters, but rather page lifecycle methods. They do not indicate when a page has been navigated to or from. You can have instances where a parent page can be appearing at the same time as multiple child pages are appearing. This will be addressed when Xamarin provides a proper navigation API.
I am a beginner in libgdx and was wondering in what cases you would need to use a constructor when switching screens (examples would be helpful). Is it to save memory? Also, is it better to create instances of all the screens in the main class that extends the game?
Here is an example of instances from https://code.google.com/p/libgdx-users/wiki/ScreenAndGameClasses :
public class MyGame extends Game {
MainMenuScreen mainMenuScreen;
AnotherScreen anotherScreen;
#Override
public void create() {
mainMenuScreen = new MainMenuScreen(this);
anotherScreen = new AnotherScreen(this);
setScreen(mainMenuScreen);
}
}
The constructor is in the next class:
public class MainMenuScreen implements Screen {
MyGame game; // Note it's "MyGame" not "Game"
// constructor to keep a reference to the main Game class
public MainMenuScreen(MyGame game){
this.game = game;
}
...
You should avoid creating all screens in Game class in create() method (you will allocate much memory at once and pointlesly). Create only one screen at a time when do you need It. So e.g. you click button New game in menu and there you call game.setScreen(new NextScreen(this));
You do not have to make constructor with Game parameter - but you will not have reference to the main Game class. Having reference to main game class is good for changing screens, method setScreen(screen).
You need the constructor because your changing to a screen that doesnt extend the Game class which is what u need to call setScreen(); Since ur passing the game class to the constructor you can use it to get back to the screen you were at (or another screen) without creating another class that extends Game
I prefer using a singleton.
Something like
public class MyGame extends Game {
private static MyGame myGame;
public static MyGame getInstance() {
if (myGame == null) {
myGame = new MyGame();
}
return myGame;
}
#Override
public void create() {
setScreen(new MainMenuScreen();
}
}
And the example for desktop main class
public class Main {
public static void main(String[] args) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.width = 800;
cfg.height = 480;
new LwjglApplication(MyGame.getInstance(), cfg);
}
}
Now whenever you need to change your screen use MyGame.getInstance().setScreen(new ScreenName());
I am kinda unclear on how to pass data to other views. I gathered there are 3 ways to do this but I not sure how to do 2 of them.
Send data through messenger(not sure if you can send objects otherwise I can see thing getting pretty messy if you have to send like 10 pieces of data or something like that along).
Somehow pass the data through the constructor of the new view model. I say "somehow" as I am unclear how to do that when using an IOC container(in this case the built in one).
Passing the data through a parameter. I seen a couple of tutorials that show you how to do navigation for the windows phone but none really talk about parameter passing. I am guessing this would still be an option.
From what I heard is that Option 1 is sort of the old way of doing it. Option 2 seems to be a newer way and better way to do it but I cannot find any examples on people showing how to do it.
I don't know how to do it because the Ioc should be creating the instance of the view so how do you pass in data into it when that data does not exist?
The two main ways I do this is:
1)Use the messenger:
Sender class:
public class TrafficLight
{
public string Color{get;set;}
public TimeSpand Duration{get;set;}
}
public class TrafficLightService
{
public void SendLight(TrafficLight light)
{
Messenger.Default.Send(light);
}
}
Receiver:
public class MyViewModel
{
public MyViewModel()
{
Messenger.Default.Register<TrafficLight>(DoSomethingWithTrafficLight);
}
private void DoSomethingWithTrafficLight(TrafficLight light)
{
}
}
What happens here is that the source object is using the Messenger as an event broker. Object A doesn't need to know about object B, they just both need to know about the messenger.
2)
Just use dependency injection:
public class TrafficLight
{
public string Color{get;set;}
public TimeSpand Duration{get;set;}
}
public class LightEventArgs:EventArgs
{
public LightEventArgs(TrafficLight light)
{
_light=light;
}
public TrafficLight Light{get{return _light;}}
}
public interface ITrafficLightService
{
void SendLight(TrafficLight light);
public event EventHandler<LightEventArgs> TrafficLightSet;
}
public class TrafficLightService
{
public void SendLight(TrafficLight light)
{
Messenger.Default.Send(light);
}
public event EventHandler<LightEventArgs> TrafficLightSet;
}
public class TrafficLightSenderViewModel
{
public TrafficLightSenderViewModel(ITrafficLightService trafficLightService)
{
_trafficLightService=trafficLightService;
_trafficLightService.Send(new TrafficLight{Color="Red"});
}
}
public class TrafficLightReceiverViewModel
{
public TrafficLightReceiverViewModel(ITrafficLightService trafficLightService)
{
_trafficLightService=trafficLightService;
_trafficLightService.TrafficLightSet+= TrafficLightNotification;
}
private void TrafficLightNotification(TrafficLightEventArgs args)
{
DoSomethingWithTheLight(args.Light);
}
}
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<ITrafficLightService, Design.TrafficLightService>();
}
else
{
SimpleIoc.Default.Register<ITrafficLightService, TrafficLightService>();
}
SimpleIoc.Default.Register<TrafficLightSenderViewModel>();
SimpleIoc.Default.Register<TrafficLightReceiverViewModel>();
}
public MainViewModel Sender
{
get { return SimpleIoc.Default.GetInstance<TrafficLightSenderViewModel>(); }
}
public MainViewModel Receiver
{
get { return SimpleIoc.Default.GetInstance<TrafficLightReceiverViewModel>(); }
}
}
This is a bigger example and more complex.
Lets walk through this step by step:
In MVVM Light we use the ViewModelLocator for 2 things: 1)To register all our viewmodels and services.
Provide a way to allow the View to get a viewmodel in XAML
When we try to resolve a ViewModel
SimpleIoc.Default.GetInstance<TrafficLightReceiverViewModel>();
SimpleIoc looks at whether the viewmodel has any dependencies. In our case we do, we need an ITrafficLightService for both our viewmodels. What happens is that SimpleIoc sees if it can resolve that class and, in the process, checks to see if ITrafficLightService has any dependencies that need resolving as well. If SimpleIoc can resolve the chain of dependencies required to instantiate your viewmodel it does so and then hands back a fully built object.
I've got the following code
public delegate void NotificacaoScanner(NotifScanner e);
// interface
public interface IScanner
{
event NotificacaoScanner onFinalLeitura;
}
// abstract class that implements the interface
public abstract class ScannerGCPerif : IScanner
{
public virtual event NotificacaoScanner onFinalLeitura;
{
add { throw new NotImplementedException("Event not available for this service"); }
remove { throw new NotImplementedException("Event not available for this service"); }
}
}
// concrete class that implements the abstract class
public class ScannerBurroughs : ScannerGCPerif
{
public override event NotificacaoScanner onFinalLeitura;
}
Why when I subscribe the onFinalLeitura event of a ScannerBurroughs instance, it insists on execute the event declaration of the base class (ScannerGCPerif), where the exception is?
I ran your code and I did not get an exception. Let me explain what happens:
You override the event in your concrete class, but you do not provide implementation for adding and removing event handlers so the compiler generates the following code:
public class ScannerBurroughs : ScannerGCPerif
{
private NotificacaoScanner _onFinalLeitura; // Declare a private delegate
public override event NotificacaoScanner onFinalLeitura
{
add { _onFinalLeitura += value; }
remove { _onFinalLeitura -= value; }
}
}
Behind the scenes it adds a private delegate and autoimplements the add / remove event accessors. The base implementation never gets called when you subscribe. Try explicitly implementing the accessors, put some breakpoints in your code and see what happens.
How to call non static method in android ?? I have try all way I can, but nothing. i have try this code in java and success for running, but why in android always error.
Here is the code of main activity.
public class Main extends Activity{
private Coba mstatus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View v)
{
switch (v.getId()){
case R.id.download:
....
break;
case R.id.resume:
mstatus.resume();
break;
}
}
This is the second class.
public abstract class Coba implements runnable{
....
public void resume(){
download();
}
public void download() {
mThread = new Thread(this);
mThread.start();
}
}
I want to call resume() method. In my source code nothing warning and error but when I try to call this method it's always force close. Is there another way to call non static method from another class ??
It's rather a java issue than an Android one:
First Coba is abstract so you should use a non abstract class, let's call this class CobaImpl
or make Coba a non abstract class (you choose).
Second you should create an instance of the class to use a non static method (eg mstatus = new CobaImpl(...) elsewhere you can use only static method.