Text In-screen Implementation in java-libGDX - java

I have some trouble with implementing a feature to show and use the player's username. I'm making a crossplatform app between windows and android where I'm trying to showcase the player's name as soon as they start typing and can press enter to proceed or press the Level Selection-button to proceed to the next screen. Every time I press ''Enter'' though, it crashes. Also, doesn't it display or take in the player's name. I know the code is not optimal as I made multiple tables for example but I was hoping somebody could tell me where I made my mistake so it would maybe work. Thanks in advance!
This is the code:
package com.paladinzzz.game.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.viewport.FillViewport;
import com.paladinzzz.game.CrossplatformApp;
import com.paladinzzz.game.util.Constants;
import com.paladinzzz.game.audio.MusicHandler;
import static com.badlogic.gdx.Gdx.input;
import static com.paladinzzz.game.screens.MenuScreen.musicHandler;
public class LoginScreen implements Screen {
private CrossplatformApp game;
private Stage stage;
private ImageButton backButton, playButton;
private Texture backTexture, playTexture, background;
private Drawable drawableBack, drawablePlay;
private OrthographicCamera camera;
BitmapFont font = new BitmapFont();
int[] x = new int[255];
public static boolean inPlayscreen = false;
public static String playername = "";
private boolean isConverted = false;
private Table table, table2;
public LoginScreen(CrossplatformApp game) {
this.game = game;
this.camera = new OrthographicCamera();
this.stage = new Stage(new FillViewport(Constants.WIDTH, Constants.HEIGHT, camera));
this.playTexture = new Texture("Screens/LoginScreen/LvlSelection.png");
this.backTexture = new Texture("Screens/BackButton.png");
this.background = new Texture("Screens/LoginScreen/loginscreen.png");
}
#Override
public void show() {
//Give the texture of the backButton to a new ImageButton
drawableBack = new TextureRegionDrawable(new TextureRegion(backTexture));
backButton = new ImageButton(drawableBack);
backButton.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(new MenuScreen(game));
MenuScreen.musicHandler.stopMusic();
}
});
//Give the texture of the playButton to a new ImageButton
drawablePlay = new TextureRegionDrawable(new TextureRegion(playTexture));
playButton = new ImageButton(drawablePlay);
playButton.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(new LevelScreen(game));
inPlayscreen = true;
}
});
//Elements can be added here to the stage
input.setInputProcessor(stage);
//A table gets made with the button which leads to the level selection screen
table = new Table();
table.bottom();
table.setFillParent(true);
table.add(playButton).padBottom(40);
stage.addActor(table);
//A table gets made with the button which leads back to the main menu
table2 = new Table();
table2.bottom();
table2.setFillParent(true);
table2.add(backButton).padBottom(13).padRight(640);
table2.row();
stage.addActor((table2));
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if(Gdx.input.isKeyJustPressed(Input.Keys.ENTER)){
game.setScreen(new LevelScreen(game));
inPlayscreen = true;
if (!isConverted){
playername = playername.substring(0, 1).toUpperCase() + playername.substring(1, playername.length()).toLowerCase();
isConverted = true;
}
}
game.batch.begin();
//A possibility gets made to insert the name of the player
game.batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
for (int i : x) {
if (input.isKeyJustPressed(i)){
if (i != 62 && i != 67 && i!= 66) {
playername += Input.Keys.toString(i).toLowerCase();
} else if (i == 67 & playername.length() > 0){
playername = playername.substring(0, playername.length() - 1).toLowerCase();
} else {
playername += " ";
}
}
}
font.draw(game.batch, playername, 0, 0);
game.batch.end();
stage.draw();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
stage.dispose();
}
}
This is how the ''LoginScreen'' looks like:
GameScreen
This is the error message:
Exception in thread "LWJGL Application"
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.substring(String.java:1963)
at com.paladinzzz.game.screens.LoginScreen.render(LoginScreen.java:108)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.paladinzzz.game.CrossplatformApp.render(CrossplatformApp.java:30)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:225)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)
Debugging with breakpoint:

The crash solution is for this line:
playername = playername.substring(0, 1).toUpperCase() + playername.substring(1, playername.length()).toLowerCase();
your second substring needs to use
playername.length()-1

Related

How to not resize but move widgets when screen resized?

I have added buttons to my code, but when I go to "resize", they get bigger or wider and it looks very bad. How can I resize the window and keep the button aspect ratio?
This is my code:
1)Main:
`package com.mygdx.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.mygdx.game.screen.MainMenuScreen;
public class gamename extends Game {
public static final int WIDTH = 760;
public static final int HEIGHT = 520;
public SpriteBatch batch;
#Override
public void create() {
batch = new SpriteBatch();
this.setScreen(new MainMenuScreen(this));
}
#Override
public void render(){
super.render();
}
}`
2)And this is the menu, here i use the image to view the buttons. MainMenu:
package com.mygdx.game.screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.mygdx.game.gamename;
public class MainMenuScreen implements Screen{
private static final int PLAY_BUTTON_WIDTH = 150;
private static final int PLAY_BUTTON_HEIGHT = 80;
private static final int OPTIONS_BUTTON_WIDTH = 150;
private static final int OPTIONS_BUTTON_HEIGHT = 80;
gamename game;
Texture playButtonActive;
Texture playButtonInactive;
Texture optionsButtonActive;
Texture optionsButtonInactive;
public MainMenuScreen (gamename game){
this.game = game;
playButtonActive = new Texture("play1.png");
playButtonInactive = new Texture("play2.png");
optionsButtonActive = new Texture("options1.png");
optionsButtonInactive = new Texture("options2.png");
}
#Override
public void show() {
}
#Override
public void render(float f) { //Colore e carica bottoni
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
game.batch.begin();
game.batch.draw(playButtonActive, 240, 150, PLAY_BUTTON_WIDTH, PLAY_BUTTON_HEIGHT);
game.batch.end();
}
#Override
public void resize(int i, int i1) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
I would like the button to be the same even if I manually increase the page size. Some say they use viewport but I have never used it and I don't know how to do it. Can someone help me?

how to do Junit test for a Libgdx class has pictures and pictures button

the Menu Class
package com.gdx.game.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.gdx.game.HuntersGame;
public class InfoScreen implements Screen {
HuntersGame game;
Texture background,backBefore,backAfter,textInfo;
/**
* Constructor, Links the Game instance
* #param game the Game instance provided by the GameScreen, contains the sprite batch
* which is essential for rendering
*/
public InfoScreen(HuntersGame game){
this.game = game;
//play button as image
backBefore = new Texture("backBefore.png");
backAfter = new Texture("backAfter.png");
//text
textInfo = new Texture("info.png");
//background
background = new Texture("grass-info.jpg");
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//positions of back button
int xb= backBefore.getWidth();
int yb= backBefore.getHeight();
//positions of the mouse
int x=Gdx.input.getX(),y=Gdx.input.getY();
//start batch
game.batch.begin();
game.batch.draw(background,0,0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
game.batch.draw(textInfo,0,-30,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
//start script for touch and click by mouse
if(x>=0 && x<=backBefore.getWidth() && y>=0 && y<=backBefore.getHeight()){
game.batch.draw(backAfter,0,Gdx.graphics.getHeight()-backBefore.getHeight());
if(Gdx.input.isTouched()){
this.dispose();
game.setScreen(new MenuScreen(game));
}
}else{
game.batch.draw(backBefore,0,Gdx.graphics.getHeight()-backBefore.getHeight());
}
game.batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
I wanted to do a test for this class I don't know how and I tried to import Mockito as every other code did but not work with me I tried for like 6 hours with no result cause I don't know how that Mockito works and search too much with no benefits and I want just an example for that class then I will try to do advanced examples
thank you in advance
PS: for the images i used you can use any image to check the code and for HunterGame class is down
package com.gdx.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.gdx.game.screens.GameScreen;
import com.gdx.game.screens.MenuScreen;
public class HuntersGame extends Game {
public SpriteBatch batch;
#Override
public void create () {
batch = new SpriteBatch();
this.setScreen(new MenuScreen((this)));
}
#Override
public void dispose () {
batch.dispose();
}
}
[the info class looks like][1]

".txt file not found" when trying to read/write in it on local storage - Libgdx, Android studio

I am making a simple game on Android studio with Libgdx and I am recording my highscore as a simple integer in a txt file which is located in the android>assets folder. In my GameOverState my current score is compared with the score in the text file and if it is bigger it is replaced in the txt file.
Also every time I am in the MenuState the High Score is read from teh file and displayed as a BitmapFont. Problem is: When I run it on the Desktop it works perfectly but when I lauch it in the emulator an error occurs:
com.badlogic.gdx.utils.GdxRuntimeException: File not found: hs.txt (Local)
And this is my GameOverState:
package com.asya.game.states;
import com.asya.game.Ozone;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class GameOverState extends state {
public int sc;
private Texture bgr;
private BitmapFont scoreFont;
public String txtScore;
public Integer hs;
public SaveHS saving;
public GameOverState(GameStateManager gsm, int score) {
super(gsm);
bgr = new Texture("gameOver.png");
sc = score;
scoreFont = new BitmapFont();
scoreFont.setColor(Color.WHITE);
//write to file if score is greater than the previous score
FileHandle file = Gdx.files.local("hs.txt");
txtScore = file.readString();
hs = Integer.parseInt(txtScore);
if (score > hs){
hs = score;
txtScore = Integer.toString(hs);
file.writeString(txtScore, false);
}
/*
saving = new SaveHS();
hs = saving.Load();
if (score > hs) {
hs = score;
saving.Save(score);
}
*/
cam.setToOrtho(false, Ozone.WIDTH, Ozone.HEIGHT);
}
#Override
protected void handleInput() {
if(Gdx.input.justTouched())
gsm.set(new MenuState(gsm));
}
#Override
public void update(float dt) {
handleInput();
}
#Override
public void render(SpriteBatch sb) {
sb.begin();
sb.setProjectionMatrix(cam.combined);
sb.draw(bgr, cam.position.x - (cam.viewportWidth / 2), 0);
scoreFont.draw(sb, "SCORE: " + sc, cam.position.x / 2 + 140, cam.position.y + 200);
sb.end();
}
#Override
public void dispose() {
bgr.dispose();
scoreFont.dispose();
}
}
And this is my MenuState:
package com.asya.game.states;
import com.asya.game.Ozone;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.GdxRuntimeException;
import java.io.FileNotFoundException;
import java.io.ObjectOutputStream;
public class MenuState extends state implements InputProcessor{
private Texture background;
private Texture playBtn, helpBtn;
private Vector2 posPlayBtn, posHelpBtn;
private Rectangle boundPlayBtn, boundHelpBtn;
private String highScore;
private BitmapFont hScoreFont;
public SaveHS saving;
public int s;
public MenuState(GameStateManager gsm) {
super(gsm);
background = new Texture("bgr.png");
playBtn = new Texture("play.png");
helpBtn = new Texture("help.png");
cam.setToOrtho(false, Ozone.WIDTH, Ozone.HEIGHT);
posPlayBtn = new Vector2((Ozone.WIDTH / 2)- (playBtn.getWidth()/2), Ozone.HEIGHT/2 +playBtn.getHeight()/2);
posHelpBtn = new Vector2((Ozone.WIDTH / 2) - (helpBtn.getWidth() / 2), Ozone.HEIGHT / 2 - helpBtn.getHeight() / 2);
boundPlayBtn = new Rectangle(posPlayBtn.x, posPlayBtn.y, playBtn.getWidth(), playBtn.getHeight());
boundHelpBtn = new Rectangle(posHelpBtn.x, posHelpBtn.y, helpBtn.getWidth(), helpBtn.getHeight());
hScoreFont = new BitmapFont();
hScoreFont.setColor(Color.WHITE);
FileHandle file = Gdx.files.local("hs.txt");
highScore = file.readString();
/*
saving = new SaveHS();
s = saving.Load();
*/
Gdx.input.setInputProcessor(this);
}
#Override
public void handleInput() {
}
#Override
public void update(float dt) {
handleInput();
}
#Override
public void render(SpriteBatch sb) {
//open sprite batch and close when done
sb.setProjectionMatrix(cam.combined);
sb.begin();
sb.draw(background, cam.position.x - (cam.viewportWidth / 2), 0); //image, starting from coordinate 0, 0 (bottom left corner) and width and heiht
hScoreFont.draw(sb, "HIGH SCORE: " + highScore, cam.position.x / 2 + 140, cam.position.y + 200);
sb.draw(playBtn, posPlayBtn.x, posPlayBtn.y);
sb.draw(helpBtn, posHelpBtn.x, posHelpBtn.y );
sb.end();
}
#Override
public void dispose() {
background.dispose();
playBtn.dispose();
helpBtn.dispose();
hScoreFont.dispose();
System.out.println("Menu State Disposed");
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if(boundPlayBtn.contains(Gdx.graphics.getWidth() - screenX, Gdx.graphics.getHeight() - screenY)){
gsm.set(new playState(gsm));
}
if(boundHelpBtn.contains(Gdx.graphics.getWidth() - screenX, Gdx.graphics.getHeight() - screenY)){
gsm.set(new helpingState(gsm));
}
return false;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
}
Why not use Preferences, find out more information here.
It handles all saving across all devices and is part of the libGDX API.
// Get an instance
Preferences prefs = Gdx.app.getPreferences("Highscores");
// Save a high score
prefs.putInteger("high1", 999);
// Make sure it is saved
prefs.flush();
// Get the high score (the 0 is default, in case no high1 is set yet)
int high1 = prefs.getInteger("high1", 0);
You shouldn't really be saving highscores in a .txt when the API provides a means of doing this.

Android Wear Watch Face Development Colors

I am trying to develop watch faces, and I was able to add the time, date, and other information and position the text. I had trouble with style, mostly color. I have one red text, and another white text. After going to Ambient Mode and turning back to interactive mode, the color is either white or gray depending on the code below. I can only get it to return to one color.
SimpleWatchFaceService.java
package com.me.me.androidwearweather;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.support.wearable.watchface.WatchFaceStyle;
import android.view.SurfaceHolder;
import java.util.concurrent.TimeUnit;
public class SimpleWatchFaceService extends CanvasWatchFaceService {
#Override
public Engine onCreateEngine() {
return new SimpleEngine();
}
private class SimpleEngine extends CanvasWatchFaceService.Engine {
private final long TICK_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(1);
private Handler timeTick;
private SimpleWatchFace watchFace;
#Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(SimpleWatchFaceService.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
.setAmbientPeekMode(WatchFaceStyle.AMBIENT_PEEK_MODE_HIDDEN)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.build());
timeTick = new Handler(Looper.myLooper());
startTimerIfNecessary();
watchFace = SimpleWatchFace.newInstance(SimpleWatchFaceService.this);
}
private void startTimerIfNecessary() {
timeTick.removeCallbacks(timeRunnable);
if (isVisible() && !isInAmbientMode()) {
timeTick.post(timeRunnable);
}
}
private final Runnable timeRunnable = new Runnable() {
#Override
public void run() {
onSecondTick();
if (isVisible() && !isInAmbientMode()) {
timeTick.postDelayed(this, TICK_PERIOD_MILLIS);
}
}
};
private void onSecondTick() {
invalidateIfNecessary();
}
private void invalidateIfNecessary() {
if (isVisible() && !isInAmbientMode()) {
invalidate();
}
}
#Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
startTimerIfNecessary();
}
#Override
public void onDraw(Canvas canvas, Rect bounds) {
super.onDraw(canvas, bounds);
watchFace.draw(canvas, bounds);
}
#Override
public void onAmbientModeChanged(boolean inAmbientMode) {
super.onAmbientModeChanged(inAmbientMode);
watchFace.setAntiAlias(!inAmbientMode);
watchFace.setColor(inAmbientMode ? Color.GRAY : Color.WHITE);
// THIS IS WERE I THINK THE PROBLEM IS I tried the method on top and bottom of this comment
// if(inAmbientMode){
// watchFace.setColor(Color.GRAY);
// }
invalidate();
}
#Override
public void onTimeTick() {
super.onTimeTick();
invalidate();
}
#Override
public void onDestroy() {
timeTick.removeCallbacks(timeRunnable);
super.onDestroy();
}
}
}
SimpleWatchFace.java
package com.me.me.androidwearweather;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.format.Time;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class SimpleWatchFace {
private final Paint timePaint;
private final Paint datePaint;
private final Time time;
public static SimpleWatchFace newInstance(Context context) {
Paint timePaint = new Paint();
timePaint.setColor(Color.RED);
timePaint.setTextSize(context.getResources().getDimension(R.dimen.time_size));
timePaint.setAntiAlias(true);
Paint datePaint = new Paint();
datePaint.setColor(Color.WHITE);
datePaint.setTextSize(context.getResources().getDimension(R.dimen.date_size));
datePaint.setAntiAlias(true);
return new SimpleWatchFace(timePaint, datePaint, new Time());
}
SimpleWatchFace(Paint timePaint, Paint datePaint, Time time) {
this.timePaint = timePaint;
this.datePaint = datePaint;
this.time = time;
}
public void draw(Canvas canvas, Rect bounds) {
time.setToNow();
canvas.drawColor(Color.BLACK);
Calendar cal = Calendar.getInstance();
SimpleDateFormat twelvehour = new SimpleDateFormat("h");
SimpleDateFormat ampm = new SimpleDateFormat("a");
String TimeAmPmNoSec = String.format("%2s:%02d %2s", twelvehour.format(cal.getTime()), time.minute, ampm.format(cal.getTime()));
float timeXOffset = computeXOffset(TimeAmPmNoSec, timePaint, bounds);
float timeYOffset = computeTimeYOffset(TimeAmPmNoSec, timePaint, bounds);
canvas.drawText(TimeAmPmNoSec, timeXOffset, timeYOffset, timePaint);
SimpleDateFormat month_date = new SimpleDateFormat("MMM");
SimpleDateFormat day_text = new SimpleDateFormat("E");
String DateNew = String.format("%s | %s %02d", day_text.format(cal.getTime()), month_date.format(cal.getTime()), time.monthDay);
float dateXOffset = computeXOffset(DateNew, datePaint, bounds);
float dateYOffset = computeDateYOffset(DateNew, datePaint);
canvas.drawText(DateNew, dateXOffset, timeYOffset + dateYOffset, datePaint);
}
private float computeXOffset(String text, Paint paint, Rect watchBounds) {
float centerX = watchBounds.exactCenterX();
float timeLength = paint.measureText(text);
return centerX - (timeLength / 2.0f);
}
private float computeTimeYOffset(String timeText, Paint timePaint, Rect watchBounds) {
float centerY = watchBounds.exactCenterY();
Rect textBounds = new Rect();
timePaint.getTextBounds(timeText, 0, timeText.length(), textBounds);
int textHeight = textBounds.height();
return centerY + (textHeight / 2.0f) - 50f;
}
private float computeDateYOffset(String dateText, Paint datePaint) {
Rect textBounds = new Rect();
datePaint.getTextBounds(dateText, 0, dateText.length(), textBounds);
return textBounds.height() + 25f;
}
public void setAntiAlias(boolean antiAlias) {
timePaint.setAntiAlias(antiAlias);
datePaint.setAntiAlias(antiAlias);
}
public void setColor(int color) {
timePaint.setColor(color);
datePaint.setColor(color);
}
}
I was also wondering if it is possible to style a text with more than one font and color.
EDIT 2: Alright, you could just instantiate a new watch face each time the mode is changed (Java will automatically garbage collect the old one, so no worries on memory) OR, I personally would do this.
Add two new functions in your SimpleWatchFace class to replace your setColor function
public void setTimeColor(int color) {
timePaint.setColor(color);
}
public void setDateColor(int color) {
datePaint.setColor(color);
}
then change your function to be this
#Override
public void onAmbientModeChanged(boolean inAmbientMode) {
super.onAmbientModeChanged(inAmbientMode);
watchFace.setAntiAlias(!inAmbientMode);
if(inAmbientMode)
{
watchFace.setTimeColor(Color.BLACK);
watchFace.setDateColor(Color.GREY);
}
else
{
watchFace.setTimeColor(Color.RED);
watchFace.setDateColor(Color.WHITE);
}
}
When the watch is put into Ambient Mode the screen turns itself black and white (or black and grey as you're experiencing)
Note: In low-bit ambient mode, the system does not reliably render the
colors in the image
from The Android Webpage

Libgdx- How to scale animation

I want to In the click the screen then Slide ya animated change the screen.
this code has been only the change the image but it has not animated . I want to change the image on the click of screen is animated and then change.. Only change the image is code is bellow but how to animated is not know???
package com.check;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.ui.Window;
import com.badlogic.gdx.utils.ArrayMap;
public class TutorialUI implements Screen, ApplicationListener{
private static final String TEXTURE_PATH = "data/animvs-logo.png";
private AssetManager assetManager;
private SpriteBatch batch;
private Stage stage;
private boolean tuchb=true;
private ArrayMap<Integer, Item> items;
private ArrayMap<Integer, Item> itemsDisplayed;
private Skin uiSkin;
private Table scrollTable;
private TextField textSearch;
private String searchLastCriteria;
TextButton button;
TextButtonStyle textButtonStyle;
TextureAtlas buttonAtlas;
BitmapFont font;
Texture logo,logo1,logo2;
Window window;
#Override
public void create() {
batch = new SpriteBatch();
stage = new Stage();
items = new ArrayMap<Integer, Item>();
itemsDisplayed = new ArrayMap<Integer, Item>();
Gdx.input.setInputProcessor(this.stage);
assetManager = new AssetManager();
assetManager.load("data/animvs-logo.png", Texture.class);
assetManager.load("data/uiskin.atlas", TextureAtlas.class);
assetManager.finishLoading();
uiSkin = new Skin(Gdx.files.internal("data/uiskin.json"), assetManager.get("data/uiskin.atlas", TextureAtlas.class));
scrollTable = new Table();
scrollTable.setCenterPosition(250, 400);
criaItens(10);
window = new Window("Animvs - UI / ScrollPane Tutorial", uiSkin);
window.setBounds(0, 100, 500, 500);
textSearch = new TextField("", uiSkin);
textSearch.addListener(new InputListener() {
public boolean keyDown(InputEvent event, int keycode) {
if (keycode == Keys.ENTER)
rearrangeTable();
return super.keyDown(event, keycode);
}
});
stage.addActor(scrollTable);
}
int tuch=1;
#Override
public void render() {
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 60f));
Gdx.gl.glClearColor(0, 0.2f, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
stage.draw();
batch.end();
if(Gdx.input.justTouched()){
if(tuch<9 && tuchb){
tuch=tuch+1;
rearrangeTable();
}
}
}
#Override
public void resize(int width, int height) {
batch.getProjectionMatrix().setToOrtho2D(0f, 0f, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// stage.setViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
rearrangeTable();
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
// Don't forget to free unmanaged objects:
batch.dispose();
uiSkin.dispose();
stage.dispose();
}
private final void criaItens(int total) {
items.clear();
itemsDisplayed.clear();
for (int i = 0; i <total ; i++) { // imagearr
Color novaCor = new Color(MathUtils.random(0.5f), MathUtils.random(0.5f), MathUtils.random(0.5f), 1f);
items.put(i, new Item(i, "Item " + i, assetManager.get(TEXTURE_PATH, Texture.class), novaCor, uiSkin));
// items.put(i, new Item(i, "Item " + i,imagearr.get(i), novaCor, uiSkin));
}
}
private final void rearrangeTable() {
scrollTable.clear();
computeDisplayedItems(textSearch.getText());
for (int i = 0; i < tuch; i++) {
addImage(tuch);
}
}
public final void addImage(int indice) {
scrollTable.add(itemsDisplayed.getValueAt(indice).getImage())
.minHeight(500)
.minWidth(500)
.center().expand();
}
private final void computeDisplayedItems(String searchCriteria) {
if ((searchCriteria == null && searchLastCriteria == null) || searchCriteria.equals(searchLastCriteria)) {
if (items.size != itemsDisplayed.size) {
itemsDisplayed.clear();
itemsDisplayed.putAll(items);
}
return;
}
itemsDisplayed.clear();
if (searchCriteria == null || searchCriteria.isEmpty()) {
itemsDisplayed.putAll(items);
return;
}
for (int i = 0; i < items.size; i++) {
if (items.getValueAt(i).getDescription().getText().toString().contains(searchCriteria))
itemsDisplayed.put(items.getKeyAt(i), items.getValueAt(i));
}
searchLastCriteria = searchCriteria;
}
#Override
public void render(float delta) {
// TODO Auto-generated method stub
}
#Override
public void show() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
}
An other class......
package com.check;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
public final class Item {
private final class ImageClick extends ClickListener {
private Item item;
public ImageClick(Item item) {
this.item = item;
}
public void clicked(InputEvent event, float x, float y) {
if(item.getId()==0){
// game.setScreen(new PowerScreen(game));
}
Gdx.app.log("SELECTED ITEM", "ID: " + item.getId() + " Description: " + item.getDescription().getText());
}
}
private int id;
private Label description;
private Image image;
private Color color;
public final int getId() {
return id;
}
public final Label getDescription() {
return description;
}
public final Image getImage() {
return image;
}
public final Color getColor() {
return color;
}
public Item(int index, String description, Texture texture, Color color, Skin skin) {
this.id = index;
this.description = new Label(description, skin);
this.image = new Image(texture);
this.color = color;
image.setColor(color);
image.addListener(new ImageClick(this));
}
}
See the answer for this link of this Question https://github.com/krustnic/HorizontalSlidingPane

Categories