2013-12-20 140 views
0

我有使用findViewById的問題。它返回null。 我正在創建一個遊戲,我有一個活動,這是我的菜單。從那裏我創建並啓動我的SurfaceView。 但我無法使用findViewById獲取對FPS TextView的引用。findViewById返回null

public class SplashScreen extends Activity { 

    . 
    . 
    . 

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

     setContentView(R.layout.splash_screen_layout); 

     . 
     . 
     . 

    } 

    private void prepareButtonListeners() { 
     this.mStartButton.setOnClickListener(new OnClickListener() {    
      @Override 
      public void onClick(View v) { 
       setContentView(R.layout.road_view_layout); 
      } 
     }); 
     . 
     . 
     . 


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

    <br.com.roadrun.RoadView 
     android:id="@+id/road_view" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" /> 

    <RelativeLayout 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" > 

     <TextView 
     android:id="@+id/fps_text_view" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerInParent="true" /> 

    </RelativeLayout> 

</FrameLayout> 


public class RoadView extends SurfaceView implements SurfaceHolder.Callback { 

    private Context mContext = null; 
    private SurfaceHolder mSurfaceHolder = null; 
    private TextView mFPSTextView = null; 

    private RoadThread mThread = null; 

    public RoadView(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     this.mContext = context; 
     this.mSurfaceHolder = getHolder(); 
     this.mSurfaceHolder.addCallback(this); 

     // THIS IS WHERE THE FINDVIEWBYID IS RETURNING NULL 
     this.mFPSTextView = (TextView) findViewById(R.id.fps_text_view); 

     setFocusable(true); 

     this.mThread = new RoadThread(this); 
    } 

你有沒有燈光?我已經嘗試在構造函數完成後在另一個方法中調用findViewById,但沒有成功。 謝謝,

+0

你的活動中的'findViewById'正在被這個內部類中的'findViewById'黯然失色。它從子視圖進行搜索,並且你的surfaceview沒有子視圖。相反,使用'SplashScreen.this.findViewById()'跳轉到範圍內。 –

+0

感謝您的回答格雷格。它不是內在的類,而是一個分離的類。正如我上面所顯示的,它看起來是一樣的,但它不是。我嘗試了這些傢伙所說的: mFPSTextView =(TextView)((SplashScreen)mContext).findViewById(R.id.fps_text_view); 螞蟻它的工作。 – Daniel

回答

0

查看的findViewById正在搜索對於給定視圖的孩子不在活動的佈局。所以你應該給Activity打電話findViewById

((Activity) getContext()).findViewById(R.id.fps_text_view)