javaandroidlibgdxandroid-assetmanager

i want to use assetmanager for an image


MyGdxGame.java

 public void print(){
    manager=new AssetManager();
    manager.load("selectlevel.png",Texture.class);
    manager.finishLoading();
    }

select level screen

 public void image(){
    Image img1=game.manager().get(("selectlevel.png"));
    }

what i get(

Exception in thread "LWJGL Application" java.lang.ClassCastException: com.badlogic.gdx.graphics.Texture cannot be cast to com.badlogic.gdx.scenes.scene2d.ui.Image

i dont want to change image type to Texture.


Solution

  • Based on your error message:

    Exception in thread "LWJGL Application" java.lang.ClassCastException: com.badlogic.gdx.graphics.Texture cannot be cast to com.badlogic.gdx.scenes.scene2d.ui.Image

    You are trying to place a Texture in a variable that is made for an scene2d.ui.Image. This will not work because a Texture and a scene2d.ui.Image are very different.

    The scene2d.ui.Image has a constructor that takes a Texture so should be called like this:

    Image imgVariable = new Image(i_am_a_Texture);
    

    In the comments you mentioned you recieved an error

    cannot resolve constructor 'Image(java.lang.Object)'

    This is saying that when you used the new Image constructor you passed it an Object and not a Texture which it was expecting.

    In order to make the Object a Texture you could cast it to a Texture by adding (Texture) in from of the object you want cast like this:

     Texture textureVariable = (Texture) game.manager().get(("selectlevel.png"));
    

    However the assetManager already has a way of saying what class the object returned should be and that is to add the class as the 2nd parameter like below

    Texture textureVariable = game.manager().get(("selectlevel.png",Texture.class))