Search code examples
androidandroid-activityglsurfaceview

Access button from Layout within GlSurfaceView


I am working on Android and have being working on OpenGL ES. I have a xml layout as follows (I have took some things out to show only therelative content:

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  xmlns:ads="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<TextView
  android:id="@+id/myText"/>

<MyGLSurfaceView
  android:id="@+id/mySurface"/>

Then in my GlSurfaceView I am trying to access the button that is in the same layout. However this is were I am having a problem.

I have tried the following:

View v = (View) getParent();
myTextViewString = (TextView) v.findViewById(R.id.myText);

this

myTextViewString = (TextView) findViewById(R.id.myText);

and this

myTextViewString = (TextView) ((RelativeLayout) getParent()).findViewById(R.id.myText);

I cannot seem to figure out how to access this button outside of the GLSurfaceView but is in the same activity inside my GLSurfaceView.java.

I do know that it has something to do with not being able to get the parent( I am assuming because it does not extend Activity). I have looked around and I cannot find a way to achieve this.


Solution

  • One clean and straightforward way to do this is to pass the button view to the GLSurfaceView. Aside from avoiding navigation through the view hierarchy, this also makes your view code more generic, since it will not have to know the id of a specific button.

    In the onCreate() method of the activity, after calling setContentView(), you could have this:

    MyGLSurfaceView glView = (MyGLSurfaceView) findViewById(R.id.mySurface);
    TextView textView = (TextView) findViewById(R.id.myText);
    glView.setTextView(textView);
    

    In MyGLSurfaceView:

    private TextView mTextView;
    
    void setTextView(TextView textView) {
        mTextView = textView;
    }
    

    Then, in other methods of MyGLSurfaceView, you can use mTextView anytime you need access to the button.