2013-12-20 139 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)