1

Я хочу разместить в XML вместе GLSurfaceView и другие элементы.

Мой xml файл:

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<LinearLayout
    android:id="@+id/mglid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="Small Button"/>

   </RelativeLayout>

Мой основной класс:

package com.mycompany.opengl2;

import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.view.Menu;
import android.widget.*;

public class MainActivity extends Activity {

/** Hold a reference to our GLSurfaceView */
public static GLSurfaceView mGLSurfaceView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mGLSurfaceView = new GLSurfaceView(this);

    // Check if the system supports OpenGL ES 2.0.
    final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
    final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;

    if (supportsEs2)
    {
        // Request an OpenGL ES 2.0 compatible context.
        mGLSurfaceView.setEGLContextClientVersion(2);

        // Set the renderer to our demo renderer, defined below.
        mGLSurfaceView.setRenderer(new LessonOneRenderer());
    }
    else
    {
        // This is where you could create an OpenGL ES 1.x compatible
        // renderer if you wanted to support both ES 1 and ES 2.
        return;
    }

    //mGLSurfaceView = (GLSurfaceView) findViewById(R.id.mglid);
    LinearLayout GLV = (LinearLayout) findViewById(R.id.mglid);
    GLV.addView(mGLSurfaceView);
    //setContentView(R.layout.main);
    //setContentView(mGLSurfaceView);
}

...дальше OnPause и т.д.

В другом классе LessonOneRenderer описывается вывод трех треугольников. Все работает, но только если запускать SetContentView(mGLSurfaceView); Лейаут же в таком случае недоступен.

Весь код взял отсюда. http://developer.alexanderklimov.ru/android/layout/framelayout.php

И сформулирую вопрос ещё раз и точно: какие мне стоит сделать движения чтобы запускать GLSurfaceView из XML и размещать на этой XML другие элементы.

0

1 ответ 1

2

Предлагаю сделать такой вариант:

1) В лейауте разместить контейнер под GLSurfaceView, что-то наподобие такого

<LinearLayout
    android:orientation="horizontal"
    android:id="@+id/renderer"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</LinearLayout>

2) Затем в OnCreate() создавать инстанс GLSurfaceView и добавлять эту вьюху в контейнер

mView = new GLSurfaceView (...);

LinearLayout renderer = (LinearLayout) findViewById(R.id.renderer);
renderer.addView(mView);

Вариант вполне рабочий, лейаут дополнительно содержит волне кликабельные элементы управления.

UPD. Пример рабочего кода

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
GLSurfaceView glSurfaceView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (!supportES()) {
        Toast.makeText(this, "OpenGl ES 2.0 is not supported", Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    glSurfaceView = new GLSurfaceView(this);
    glSurfaceView.setEGLContextClientVersion(2);
    glSurfaceView.setRenderer(new OpenGlRenderer());

    ViewGroup container = (ViewGroup) findViewById(R.id.mglid);
    container.addView(glSurfaceView);

    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "Button was clicked!", Toast.LENGTH_SHORT).show();
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    Log.e(TAG, "onResume");
    glSurfaceView.onResume();
}

@Override
protected void onPause() {
    super.onPause();
    Log.e(TAG, "onPause");
    glSurfaceView.onPause();
}

private boolean supportES() {
    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
    return configurationInfo.reqGlEsVersion >= 0x20000;
}

}

и файл разметки

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/label"
        android:text="Open GL"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"/>

<Button
    android:id="@+id/button"
    style="?android:attr/buttonStyleSmall"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:text="Small Button"/>

<LinearLayout
        android:id="@+id/mglid"
        android:layout_below="@id/label"
        android:layout_above="@id/button"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"/>

</RelativeLayout>

в добавок класс рендерера

public class OpenGlRenderer implements GLSurfaceView.Renderer {

private static final String TAG = OpenGlRenderer.class.getSimpleName();
private static final int LOG_PER_FRAMES = 10;

int count;


@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    Log.w(TAG, "onSurfaceCreated");
    count = 0;
    glClearColor(.5f, 1f, .5f, 1f);
}

@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    Log.w(TAG, "onSurfaceChanged");
    glViewport(0, 0, width, height);
}

@Override
public void onDrawFrame(GL10 gl) {
    if (count % LOG_PER_FRAMES == 0) {
        Log.v(TAG, "onDrawFrame: count = " + count);
    }
    glClear(GLES10.GL_COLOR_BUFFER_BIT);
    count++;
}

}

11
  • Пока решительно не получается. Можете помочь исходя из моего кода? пишет что ссылаюсь на пустой объект и т.д. Обновляю код в вопросе 29 окт 2015 в 20:57
  • Я полностью переписал что вы предложили, только изменил имена на свои. И все равно получил "Приложение остановлено". Уже третий день не могу понять в чем проблема. Сотни примеров пересмотрел и перепробовал :( 30 окт 2015 в 4:49
  • что бы о чем-то говорить конкретно надо видеть лог ошибки. надо понять в каком месте падает. снимите лог и выложите
    – Alex Ziko
    30 окт 2015 в 8:32
  • setContentView(R.layout.main); раскоментируйте и поставьте выше сразу за super.onCreate(savedInstanceState);
    – Alex Ziko
    30 окт 2015 в 8:36
  • Вот этот элемент в RelativeLayout. <android.opengl.GLSurfaceView android:id="@+id/mglid" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerVertical="true" android:layout_centerHorizontal="true"/> 30 окт 2015 в 11:44

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.