Как добавить libgdx в качестве дополнительного представления в android
У меня есть main.xml следующим образом:
<RelativeLayout>
...
<FrameLayout
android:id="@+id/panel_sheet"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.libgdx.Sheet3DViewGdx
android:id="@+id/m3D"
android:layout_width="1000dp"
android:layout_height="600dp"
/>
</FrameLayout>
...
</RelativeLayout>
И мой основной класс активности выглядит следующим образом:
public class Test extends Activity {
MainActivity m3DActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Мой класс GDX выглядит следующим образом, который расширяет класс ApplicationListener, а не View.
public class Sheet3DViewGdx implements ApplicationListener{
@Override
public void create() {
InputStream in = Gdx.files.internal("data/obj/Human3DModel.obj").read();
model = ObjLoader.loadObj(in);
}
@Override
public void dispose() {
}
@Override
public void pause() {
}
@Override
public void render() {
Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
model.render(GL10.GL_TRIANGLES);
}
@Override
public void resize(int arg0, int arg1) {
float aspectRatio = (float) arg0 / (float) arg1;
}
@Override
public void resume() {
}
}
Теперь, как мне добавить Sheet3DViewGdx в качестве подвью в моем основном макете?
Ответы
Ответ 1
Класс AndroidApplication (который расширяет активность) имеет метод с именем initializeForView(ApplicationListener, AndroidApplicationConfiguration)
, который вернет View
, который вы можете добавить в свой макет.
Таким образом, ваш тестовый класс может расширить приложение AndroidApplication вместо Activity, чтобы вы могли вызвать этот метод и добавить представление в свой макет.
Если это не вариант, по какой-то причине взгляните на то, что исходный код AndroidApplication, и имитируйте это.
Ответ 2
Я создал программу Hello World на github для libgdx, запущенной во фрагменте с помощью Android Studio 2.1. Он следует за инструкциями на официальной вики-странице libgdx.
![введите описание изображения здесь]()
Класс AndroidLauncher:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.badlogic.gdx.backends.android.AndroidFragmentApplication;
public class AndroidLauncher extends FragmentActivity implements AndroidFragmentApplication.Callbacks {
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
// Create libgdx fragment
GameFragment libgdxFragment = new GameFragment();
// Put it inside the framelayout (which is defined in the layout.xml file).
getSupportFragmentManager().beginTransaction().
add(R.id.content_framelayout, libgdxFragment).
commit();
}
@Override
public void exit() {
}
}
Класс GameFragment:
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.badlogic.gdx.backends.android.AndroidFragmentApplication;
public class GameFragment extends AndroidFragmentApplication{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// return the GLSurfaceView on which libgdx is drawing game stuff
return initializeForView(new MyGdxGame());
}
}
layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/content_framelayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2">
</FrameLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#FF0000"
android:textColor="#00FF00"
android:textSize="40dp"
android:text="I'm just a TextView here with red background :("/>
</LinearLayout>
Класс MyGdxGame:
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.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
private BitmapFont font;
@Override
public void create () {
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
font = new BitmapFont();
font.setColor(Color.BLUE);
}
@Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
//batch.draw(img, 0, 0);
font.getData().setScale(6.0f);
font.draw(batch, "Hello World from libgdx running in a fragment! :)", 100, 300);
batch.end();
}
@Override
public void dispose () {
batch.dispose();
img.dispose();
}
}
Убедитесь, что вы добавили следующее:
compile "com.android.support:support-v4:24.1.1"
В проект gradle script в разделе "зависимости {.}" внутри раздела проекта ( ": android" ).
Ответ 3
Использование проекта libgdx в качестве представления внутри приложения для Android теперь четко описано с помощью кода примера в libgdx wiki, реализованном как фрагмент (лучшая практика для современных приложений для Android):
- Добавьте библиотеку поддержки Android V4 в проект -android и его путь сборки, если вы еще не добавили его. Это необходимо для расширения функции FragmentActivity позже
- Измените активность AndroidLauncher для расширения функции FragmentActivity, а не AndroidApplication.
- Внедрение AndroidFragmentApplication.Callbacks в активности AndroidLauncher.
- Создайте класс, расширяющий AndroidFragmentApplication, который является реализацией фрагмента для Libgdx.
- Добавьте код initializeForView() в метод Fragment onCreateView.
- Наконец, замените содержимое активности AndroidLauncher фрагментом Libgdx.
Ответ 4
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = false;
//initialize(new LoveHearts(), cfg);
LinearLayout lg=(LinearLayout)findViewById(R.id.game);
lg.addView(initializeForView(new LoveHearts(), cfg));
}