I have tried to use this tutorial:
http://www.badlogicgames.com/forum/viewtopic.php?f=11&t=484#p2959
Firstly have declared private Toast render_toast = new Toast(7, 6);
After that putted render_toast.toaster(); to render.
I would like to use it in show, so I have put this to show():
render_toast.makeText("Game start", "font", Toast.COLOR_PREF.BLUE, Toast.STYLE.ROUND, Toast.TEXT_POS.middle_right, Toast.TEXT_POS.middle_down, Toast.MED);
It isn't working, gives no error message, only stop my application.
I have implemented Android-like toast for my project and decided to share it with you! Enjoy: Toast LibGDX (GitHub)
Create an interface for required methods in your game. Implement this method in your AndroidLauncher class, using libgdx handler. You can call these methods anywhere in your game for Android related UI.
You can follow this video for details,
https://www.youtube.com/watch?v=XxiT3pkIiDQ
This is how, I used it in my game.
//Defining interface for customized methods
public interface AndroidInterfaces {
public void toast(final String t);
}
//implementing the interface in android launcer
public class AndroidLauncher extends AndroidApplication implements AndroidInterfaces{
final AndroidLauncher context=this;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
//if (Gdx.input.isPeripheralAvailable(Peripheral.Compass))
cfg.useCompass = true;
//cfg.useAccelerometer=true;
initialize(new MyGame(this), cfg);
}
#Override
public void toast(final String t) {
handler.post(new Runnable()
{
#Override
public void run() {
//System.out.println("toatsing in launcher run");
Toast.makeText(context, t, Toast.LENGTH_SHORT).show();
}
});
}
}
public class MyGame extends Game{
//16012016
//16012016 for toast
AndroidInterfaces aoi;
public MyGame(AndroidInterfaces maoi)
{
aoi=maoi;
}
public MyGame()
{
}
public boolean backpressed=false; //Universal flag to check back button press status , across screens.
.....
.....
}
public class MainMenuScreen implements Screen{
MyGame game;
float x,y,w,h,pw,gap;
float x1,y1; //coordinates for animation
//16012016
boolean toast=false;
float toasttimer=0;
public MainMenuScreen(MyGame gg) {
game = gg;
}
#Override
public void render(float delta) {
//16012016
if(toast)
{
toasttimer=toasttimer+delta;
}
.....
...//omitted
//16012016:Toast
if(toast)
{
if(toasttimer> 2.5)
Gdx.app.exit();
else if (Gdx.input.isKeyJustPressed(Keys.BACK)) //For double back press exit effect.
Gdx.app.exit();
}
else if (Gdx.input.justTouched()) {
game.setScreen(game.STS); //Setting another screen
}
//16012016
else if (Gdx.input.isKeyJustPressed(Keys.BACK))
if(!game.backpressed)
{
if(!toast)
{
toast=true; //if bsck button is just pressed in current screen then toasting..
game.aoi.toast("EXITING.THANKS FOR PLAYING!"); //Not relevant to desktop project, calling implemented method in androind launcher
}
}
}
else if(game.backpressed)
{
game.backpressed=false;
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
//16012016
toasttimer=0;
toast=false;
Gdx.graphics.setContinuousRendering(true);
}
#Override
public void hide() {
Gdx.input.setInputProcessor(null);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
Related
I followed google guide:
updated build.gradle dependencies
updated AndroidManifest.xml
updated the AndroidLauncher and tried banner ads first
from libgdx wiki https://libgdx.com/wiki/third-party/admob-in-libgdx
#Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(), config);
// Create and setup the AdMob view
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); // Put in your secret key here
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// Add the libGDX view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}}
but I cant figure out how to do the same for Interstitial ads
i tried adding adscontroller interface
public interface AdsController {
public void loadInterstitialAd();
public void showInterstitialAd();
}
and updating AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements AdsController {
InterstitialAd mInterstitialAd;
private static final String TAG = "Androidlauncher";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// // Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(this), config);
layout.addView(gameView);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = null;
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.d(TAG, loadAdError.toString());
mInterstitialAd = null;
}
});
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.");
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d(TAG, "Ad dismissed fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.");
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.");
}
});
loadInterstitialAd();
}
#Override
public void loadInterstitialAd() {
AdRequest adRequest = new AdRequest.Builder().build();
}
#Override
public void showInterstitialAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(mInterstitialAd!=null) {
mInterstitialAd.show();
}
else loadInterstitialAd();
}
});
}
}
InterstitialAd.show(MyActivity.this); require activity but libgdx doesn't work like that(I think?)
every code I found is no longer useful because google updated Admob
AndroidApplication extends Activity, so for interstitials you can just pass in a reference to the application, eg InterstitialAd.show(this);
I did something very similar to get interstitials working in my project. I use Ironsource but the process should be very similar. First, I defined an AdManager interface:
public interface AdManager {
/**
* Show a rewarded video ad
*/
void showRewardedVideo();
/**
* Called on app pause
*/
void onPause();
/**
* Called on app resume
*/
void onResume();
/**
* Attempts to show an interstitial ad
*
* #param onSuccess
* #param onFailed
*/
void showInterstitial(Listener onSuccess, Listener onFailed);
/**
* Called every frame, for any extra work that might need to be done
*
* #param deltaTime
*/
void update(float deltaTime);
}
Following that, you can implement your platform's ad provider:
public class AndroidAdManager implements AdManager, RewardedVideoListener, InterstitialListener, OfferwallListener {
private OnlineRPG game;
private boolean videoAvailable;
private Listener onInterstitialSuccess;
private Listener onInterstitialFailed;
private float timeSinceAd;
public AndroidAdManager(Activity activity, Gamegame) {
this.game = game;
this.activity = activity;
IronSource.setRewardedVideoListener(this);
IronSource.setInterstitialListener(this);
IronSource.setOfferwallListener(this);
IronSource.init(activity, "whatever");
IronSource.shouldTrackNetworkState(activity, true);
IronSource.loadInterstitial();
IntegrationHelper.validateIntegration(activity);
}
#Override
public void showRewardedVideo() {
if (IronSource.isRewardedVideoPlacementCapped(REWARDED_VIDEO_PLACEMENT_NAME)) {
Log.i(TAG, "Rewarded video placement is capped");
return;
}
IronSource.showRewardedVideo(REWARDED_VIDEO_PLACEMENT_NAME);
}
#Override
public void onPause() {
IronSource.onPause(activity);
}
#Override
public void onResume() {
IronSource.onResume(activity);
}
#Override
public void showInterstitial(Listener onSuccess, Listener onFailed) {
if (timeSinceAd < INTERSTITIAL_MIN_PERIOD || true) {
onFailed.invoke();
return;
}
this.onInterstitialSuccess = onSuccess;
this.onInterstitialFailed = onFailed;
IronSource.showInterstitial(INTERSTITIAL_PLACEMENT_NAME);
}
#Override
public void update(float deltaTime) {
timeSinceAd += deltaTime;
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewardedVideoAvailabilityChanged(boolean b) {
Log.i(TAG, "onRewardedVideoAvailabilityChanged: " + b);
videoAvailable = b;
}
#Override
public void onRewardedVideoAdStarted() {
}
#Override
public void onRewardedVideoAdEnded() {
}
#Override
public void onRewardedVideoAdRewarded(Placement placement) {
}
#Override
public void onRewardedVideoAdShowFailed(IronSourceError ironSourceError) {
}
#Override
public void onRewardedVideoAdClicked(Placement placement) {
}
#Override
public void onInterstitialAdReady() {
}
#Override
public void onInterstitialAdLoadFailed(IronSourceError ironSourceError) {
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdOpened() {
Log.i(TAG, "Interstitial Ad Opened");
}
#Override
public void onInterstitialAdClosed() {
Log.i(TAG, "Interstitial Ad Closed");
if (onInterstitialSuccess != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
timeSinceAd = 0;
onInterstitialSuccess.invoke();
onInterstitialSuccess = null;
}
});
}
IronSource.loadInterstitial();
}
#Override
public void onInterstitialAdShowSucceeded() {
}
#Override
public void onInterstitialAdShowFailed(IronSourceError ironSourceError) {
Log.e(TAG, ironSourceError.getErrorMessage());
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdClicked() {
}
#Override
public void onOfferwallAvailable(boolean b) {
}
#Override
public void onOfferwallOpened() {
}
#Override
public void onOfferwallShowFailed(IronSourceError ironSourceError) {
}
#Override
public boolean onOfferwallAdCredited(int i, int i1, boolean b) {
return false;
}
#Override
public void onGetOfferwallCreditsFailed(IronSourceError ironSourceError) {
}
#Override
public void onOfferwallClosed() {
}
}
Lastly, in your AndroidLauncher you can create your AndroidAdManager, giving it a reference to your game/activity.
public class AndroidLauncher extends AndroidApplication {
private Game game;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
game = new Game();
game.setAdManager(new AndroidAdManager(this, game));
game.setPermissionManager(new AndroidPermissionManager(this, game));
initialize(game, config);
}
#Override
protected void onPause() {
super.onPause();
game.getAds().onPause();
}
#Override
protected void onResume() {
super.onResume();
game.getAds().onResume();
}
}
I hope this helps in your project!
I'm not new to libgdx, but when i ended up with my previous university project, and started new one, Android studio or IDEA cannot resolve setScreen method, other stuff works fine. Any ideas ? Hope for help. (project absolutely clear).
Creating a project in LibGdx gives you your core file which implements the ApplicationListener.
What I gather you are referring to is extending the Game class with with you set Screen classes with.
With the ApplicationListener.
public class HelloWorld implements ApplicationListener {
private SpriteBatch batch;
private BitmapFont font;
#Override
public void create() {
batch = new SpriteBatch();
font = new BitmapFont();
font.setColor(Color.RED);
}
#Override
public void dispose() {
batch.dispose();
font.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.begin();
font.draw(batch, "Hello World", 200, 200);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
What you're after: (taken from https://github.com/libgdx/libgdx/wiki/Extending-the-simple-game)
public class Drop extends Game {
public SpriteBatch batch;
public BitmapFont font;
public void create() {
batch = new SpriteBatch();
//Use LibGDX's default Arial font.
font = new BitmapFont();
this.setScreen(new MainMenuScreen(this));
}
public void render() {
super.render(); //important!
}
public void dispose() {
batch.dispose();
font.dispose();
}
}
Which allows you to change screens whenever you need:
public class MainMenuScreen implements Screen {
final Drop game;
OrthographicCamera camera;
public MainMenuScreen(final Drop game) {
this.game = game;
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
}
//...Rest of class omitted for succinctness.
}
For default, gdx main Class will extends ApplicationAdapter, you need extends Game class for get use of setScreen()
I have a blue square, and when the blue square is moved to the finish flag, the screen should change to signify that the level is complete. However, when I move the blue square to such position, I get an error message:
Exception in thread "LWJGL Application" org.lwjgl.opengl.OpenGLException: Cannot use offsets when Array Buffer Object is disabled
at org.lwjgl.opengl.GLChecks.ensureArrayVBOenabled(GLChecks.java:77)
at org.lwjgl.opengl.GL20.glVertexAttribPointer(GL20.java:892)
at com.badlogic.gdx.backends.lwjgl.LwjglGL20.glVertexAttribPointer(LwjglGL20.java:847)
at com.badlogic.gdx.graphics.glutils.ShaderProgram.setVertexAttribute(ShaderProgram.java:662)
at com.badlogic.gdx.graphics.glutils.VertexBufferObject.bind(VertexBufferObject.java:202)
at com.badlogic.gdx.graphics.Mesh.bind(Mesh.java:380)
at com.badlogic.gdx.graphics.Mesh.bind(Mesh.java:371)
at com.badlogic.gdx.graphics.Mesh.render(Mesh.java:479)
at com.badlogic.gdx.graphics.Mesh.render(Mesh.java:422)
at com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20.flush(ImmediateModeRenderer20.java:151)
at com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20.end(ImmediateModeRenderer20.java:160)
at com.badlogic.gdx.graphics.glutils.ShapeRenderer.end(ShapeRenderer.java:1104)
at com.badlogic.gdx.graphics.glutils.ShapeRenderer.check(ShapeRenderer.java:1087)
at com.badlogic.gdx.graphics.glutils.ShapeRenderer.polygon(ShapeRenderer.java:1014)
at com.badlogic.gdx.graphics.glutils.ShapeRenderer.polygon(ShapeRenderer.java:1043)
at com.ian.redsquare.Entities.Walls.render(Walls.java:22)
at com.ian.redsquare.Screens.RedSquareScreen.render(RedSquareScreen.java:65)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
here is the screen class in which the blue square moves:
package com.ian.redsquare.Screens;
import ...
public class RedSquareScreen implements Screen{
RedSquareGame game;
Viewport gameViewport;
ShapeRenderer renderer;
RedSquare redSquare;
BlueSquare blueSquare;
FinishSquare finishSquare;
Walls walls;
public RedSquareScreen(RedSquareGame game){
this.game = game;
}
#Override
public void show() {
gameViewport = new ExtendViewport(C.WORLD_SIZE, C.WORLD_SIZE, C.WORLD_SIZE, C.WORLD_SIZE);
renderer = new ShapeRenderer();
renderer.setAutoShapeType(true);
finishSquare = new FinishSquare(blueSquare);
redSquare = new RedSquare();
blueSquare = new BlueSquare(redSquare);
walls = new Walls();
}
#Override
public void render(float delta) {
redSquare.update(delta);
blueSquare.update(delta);
if(finishSquare.position.dst(blueSquare.position) <= 0){
game.showLevelEndScreen();
}
gameViewport.apply(true);
Gdx.gl.glClearColor(C.BACKGROUND_COLOR.r, C.BACKGROUND_COLOR.g, C.BACKGROUND_COLOR.b, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.setProjectionMatrix(gameViewport.getCamera().combined);
renderer.begin();
finishSquare.render(renderer);
redSquare.render(renderer);
blueSquare.render(renderer);
walls.render(renderer);
renderer.end();
}
#Override
public void resize(int width, int height) {
gameViewport.update(width, height, true);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
renderer.dispose();
}
#Override
public void dispose() {
}
}
here is screen class which is meant to appear once the blue square reaches the finish square:
package com.ian.redsquare.Screens;
import ...
public class LevelEndScreen extends InputAdapter implements Screen {
RedSquareGame game;
Viewport viewport;
ShapeRenderer renderer;
SpriteBatch batch;
public LevelEndScreen(RedSquareGame game){
this.game = game;
}
#Override
public void show() {
viewport = new ExtendViewport(C.LE_WORLD_SIZE, C.LE_WORLD_SIZE);
renderer = new ShapeRenderer();
renderer.setAutoShapeType(true);
batch = new SpriteBatch();
Gdx.input.setInputProcessor(this);
}
#Override
public void render(float delta) {
viewport.apply();
Gdx.gl.glClearColor(C.LE_BACKGROUND_COLOR.r, C.LE_BACKGROUND_COLOR.g, C.LE_BACKGROUND_COLOR.b, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.setProjectionMatrix(viewport.getCamera().combined);
renderer.begin(ShapeRenderer.ShapeType.Filled);
renderer.setColor(C.RESTART_COLOR);
renderer.rect(C.LE_WORLD_SIZE / 4, C.LE_WORLD_SIZE / 2, C.BUTTON_SIZE, C.BUTTON_SIZE);
renderer.setColor(C.NEXT_LEVEL_COLOR);
renderer.rect((C.LE_WORLD_SIZE * (3 / 4)) - C.BUTTON_SIZE, C.LE_WORLD_SIZE / 2, C.BUTTON_SIZE, C.BUTTON_SIZE);
renderer.end();
}
#Override
public void resize(int width, int height) {
viewport.update(width, height, true);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
batch.dispose();
renderer.dispose();
}
#Override
public void dispose() {
}
#Override
public boolean touchDown (int screenX, int screenY, int pointer, int button) {
Vector2 worldTouch = viewport.unproject(new Vector2(screenX, screenY));
if(worldTouch.dst2(new Vector2(C.LE_WORLD_SIZE / 4, C.LE_WORLD_SIZE / 2)) == 0){
game.showRedSquareScreen();
}
return true;
}
}
I have two clases, one for main methods and the other for splash. However, switching between these two doesn't work. I wanted to draw an image in the Splash class, but it turned black instantly. And when I moved the code from the splash to main class, the image appeared.
Main class:
public class Main extends Game {
public static int WIDTH, HEIGHT;
public void create () {
WIDTH = Gdx.graphics.getWidth();
HEIGHT = Gdx.graphics.getHeight();
setScreen(new Splash());
}
public void render () { }
public void dispose() { super.dispose(); }
public void pause() { super.pause(); }
public void resize(int width, int height) { super.resize(width, height); }
public void resume() { }
}
Splash class:
public class Splash implements Screen {
private Sprite splash;
private SpriteBatch sb;
public void show() {
sb = new SpriteBatch();
Texture splashTexture = new Texture(Gdx.files.internal("res/img/splash.png"));
splash = new Sprite(splashTexture);
splash.setSize(Main.WIDTH, Main.HEIGHT);
Gdx.gl.glClearColor(0, 0, 0, 1);
}
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
sb.begin();
splash.draw(sb);
sb.end();
}
public void resize(int width, int height) { }
public void resume() { }
public void dispose() { }
public void hide() { }
public void pause() { }
}
Any idea, what could cause the problem of not rendering the image in Splash class?
UPDATE 1: I have discovered, that the render() method inside the Splash class doesn't even get called (but the show() method does)
You should call the render method from your game class. If you dont call it noone will do that for you. You shouldn't override the render method of the game class which you do and you do it empty so it wont call anything for you.
Lets take a look into the Game class. It does implement all methods from the ApplicationListener interface (well not the create()). So there is no need for you to override anything of it. Simply delete your:
public void render () { }
public void dispose() { super.dispose(); }
public void pause() { super.pause(); }
public void resize(int width, int height) { super.resize(width, height); }
public void resume() { }
and it should work fine. Even though these are useless methods. They do nothing than calling the super class so why you write those. If you have not written that it automatically calls the super methods.
But okay if you want to handle the stuff yourself like calling dispose on a screen or calling the init before you set a new screen you need to write your own "game" class which implements the ApplicationListener interface.
To give you an idea on how to do this ill post a small example which i use for some tests:
public class MyGameClass implements ApplicationListener {
private Screen curScreen; // the current screen
#Override
public void create(){
Gdx.graphics.getWidth();
Gdx.graphics.getHeight();
Intro temp = new Intro(this);//just an example of the first screen to load up
setScreen(temp);
}
public void setScreen(Screen s) {
if (curScreen != null) {
curScreen.hide();
curScreen.dispose();
}
curScreen = s;
curScreen.show();
curScreen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
s.init();
}
#Override
public void dispose() {
curScreen.dispose();
}
#Override
public void render() {
curScreen.render(Gdx.graphics.getDeltaTime()); //call the rendermethod with the delta time as parameter
}
#Override
public void resize(int width, int height) {
curScreen.resize(width, height);
}
#Override
public void pause() {
curScreen.pause();
}
#Override
public void resume() {
curScreen.resume();
}
}
When _fwf.GetFileWatcher is called, always MailWatcher is returning. How can I return FileWatcher class with typed factory facility? I tried code block as below but this gets always the first component.
Also I tried DefaultTypedFactoryComponentSelector but i can't get a result.
public interface IWatcher : IDisposable
{
void StartWatching();
}
public class MailWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("Mail watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public class FileWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("File watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public interface IFileWatcherFactory : IDisposable
{
IWatcher GetWatcher(string path);
void Destroy(IWatcher fw);
}
public class Bootstrapper
{
private static WindsorContainer _container;
private static IFileWatcherFactory _fwf;
public static void Initialize()
{
_container = new WindsorContainer();
_container.AddFacility<TypedFactoryFacility>();
_container.Register(Component.For<IWatcher>().ImplementedBy<MailWatcher>().LifeStyle.Transient);
_container.Register(Component.For<IWatcher>().ImplementedBy<FileWatcher>().LifeStyle.Transient);
_container.Register(Component.For<IFileWatcherFactory>().AsFactory(x => x.SelectedWith(new FileWatcherSelector())));
_fwf = _container.Resolve<IFileWatcherFactory>();
strong textvar fw = _fwf.GetFileWatcher("file", 20);
fw.StartWatching();
}
}
For anyone looking at this, using the TypedFactoryFacility, to dictate which type the Factory will create if this varies, you can use the Get[Name] convention, where your interface will have a create method for each implementation type.
public class MailWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("Mail watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public class FileWatcher : IWatcher
{
public void StartWatching()
{
Console.WriteLine("File watcher");
}
public void Dispose()
{
throw new NotImplementedException();
}
}
public interface IFileWatcherFactory : IDisposable
{
IWatcher GetMailWatcher(string path);
IWatcher GetFileWatcher(string path);
void Destroy(IWatcher fw);
}
public class Bootstrapper
{
private static WindsorContainer _container;
private static IFileWatcherFactory _fwf;
public static void Initialize()
{
_container = new WindsorContainer();
_container.AddFacility<TypedFactoryFacility>();
_container.Register(Component.For<IWatcher>().ImplementedBy<MailWatcher>().Named("MailWatcher").LifeStyle.Transient);
_container.Register(Component.For<IWatcher>().ImplementedBy<FileWatcher>().Named("FileWatcher").LifeStyle.Transient);
_container.Register(Component.For<IFileWatcherFactory>().AsFactory());
_fwf = _container.Resolve<IFileWatcherFactory>();
var fw = _fwf.GetFileWatcher("file", 20);
fw.StartWatching();
}
}
For more information, please refer to :
http://docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx#Get_methods_lookup_components_by_name_4