2016-05-15 58 views
0

我正在使用Android,並且正在開發OpenGL ES。我有一個XML佈局如下(我已經花了一些東西出來,只顯示therelative內容:GlSurfaceView內的佈局訪問按鈕

<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內相同的活動。

我知道它與無法獲得父母(我假設,因爲它不擴展活動)有關。我環顧四周,無法找到實現這一目標的途徑。

任何幫助,非常感謝。謝謝,

+0

爲什麼不將'Context'或只是按鈕從活動傳遞到'GLSurfaceView'?然後,您不必在視圖中跳過箍環即可訪問它。 –

+0

你能提交一個關於如何完成傳遞和使用我獲得ID的答案。所以我可以標記它是正確的。這是一個有趣的想法,我沒有想到 – L1ghtk3ira

回答

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任何時候你需要訪問按鈕。

+0

真棒作品很棒,我不知道我可以通過UI對象的引用。謝謝! – L1ghtk3ira