我正在使用Android并且正在开发OpenGL ES。我有一个xml布局如下(我已经拿出一些东西只显示相关内容:
<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"/>
然后在我的GlSurfaceView中,我试图访问处于相同布局的按钮。然而,这是我遇到的问题。
我尝试了以下内容:
View v = (View) getParent();
myTextViewString = (TextView) v.findViewById(R.id.myText);
此
myTextViewString = (TextView) findViewById(R.id.myText);
和这个
myTextViewString = (TextView) ((RelativeLayout) getParent()).findViewById(R.id.myText);
我似乎无法弄清楚如何在GLSurfaceView之外访问此按钮,但在我的GLSurfaceView.java中处于相同的活动中。
我知道它与无法获取父级有关(我假设因为它没有扩展Activity)。我环顾四周,找不到实现这个目标的方法。
答案 0 :(得分:1)
一种简洁明了的方法是将按钮视图传递给GLSurfaceView
。除了避免在视图层次结构中导航之外,这还使您的视图代码更通用,因为它不必知道特定按钮的ID。
在活动的onCreate()
方法中,在致电setContentView()
后,您可以拥有以下内容:
MyGLSurfaceView glView = (MyGLSurfaceView) findViewById(R.id.mySurface);
TextView textView = (TextView) findViewById(R.id.myText);
glView.setTextView(textView);
在MyGLSurfaceView
:
private TextView mTextView;
void setTextView(TextView textView) {
mTextView = textView;
}
然后,在MyGLSurfaceView
的其他方法中,您可以在需要访问该按钮的任何时候使用mTextView
。