使用文字字段会导致应用崩溃

时间:2015-07-08 05:39:30

标签: android android-studio crash libgdx textfield

所以我刚开始学习Android Studio和LibGDX,所以我不确定如何使用Scene2d UI中的TextField或者我是否正确使用它。当我尝试在模拟器上运行它时,下面的代码崩溃了。

package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;

public class MyGdxGame extends ApplicationAdapter {

    private SpriteBatch batch;
    private BitmapFont font;
    private int screenHeight, screenWidth;
    private Skin skin;
    private TextField username, password;

    @Override
    public void create () {
        batch = new SpriteBatch();
        font = new BitmapFont();
        font.setColor(Color.GRAY);
        font.getData().scale(3);

        screenHeight = Gdx.graphics.getHeight();
        screenWidth = Gdx.graphics.getWidth();

        skin = new Skin();
        username = new TextField("Username", skin);
        password = new TextField("Password", skin);
    }

    @Override
    public void dispose() {
        batch.dispose();
        font.dispose();
        skin.dispose();
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0, 0, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();

        font.draw(batch, "Username:", (screenWidth / 2) - (screenWidth / 3),
            (screenHeight / 2) + (screenHeight / 12));
        font.draw(batch, "Password:", (screenWidth/2)-(screenWidth/3),
            ((screenHeight/2)+(screenHeight/12))-100);
        username.draw(batch, 1);
        password.draw(batch, 1);

        batch.end();
    }

}

1 个答案:

答案 0 :(得分:0)

是的,你的问题是你没有皮肤。

skin = new Skin();
username = new TextField("Username", skin);

您确实创建了一个新皮肤,但它是空的。 TextField在创建时会查找TextFieldStyle,但没有,因此您的应用程序将崩溃。

谷歌围绕如何创建一个非空皮肤,这应该可以解决你的问题。