关于findViewById返回空指针的错误

============问题描述============


今天遇到一个错误,百度了一下没能解决问题,也许搜索能力有待提高
先把部分代码贴出来
protected void onCreate(Bundle savedInstanceState) {

		

		Log.v("GameWindow", "onCreate");

		

		super.onCreate(savedInstanceState);

		setContentView(R.layout.gameview);

		

//		LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);     

//		View layout = inflater.inflate(R.layout.gameview,null);

		

//		gameView = (GameView) view.findViewById(R.id.game_sudo_view);

		

		gameView = (GameView) findViewById(R.id.game_sudo_view);

		if(gameView == null){

			Log.v("gameView", "onCreate->null");

		}

		

		levelTextView = (TextView)findViewById(R.id.leveltextview);

		levelTextView.setText("Topic."+1));

		

		if(levelTextView == null){

			Log.v("TextView", "onCreate->null");

		}

	}

下面是gameview.xml
<?xml version="1.0" encoding="utf-8" ?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:background="@drawable/back">

    

    <ImageView

	    android:layout_width="fill_parent"

	    android:layout_height="wrap_content"

	    android:layout_alignParentBottom="true"

	    android:contentDescription="@string/app_name"

	    android:src="@drawable/grass" />

    

    <com.ljx.gameview.GameView

        android:id="@+id/game_sudo_view"

        android:layout_centerInParent="true"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"/>

    

    <TextView

        android:layout_centerHorizontal="true" 

        android:layout_above="@id/game_sudo_view"

        android:id="@+id/leveltextview"

        android:layout_marginTop="10dp"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"/>

    

</RelativeLayout>

现在问题是,同样在一个布局文件中,textView可以通过findViewById获取,但自定义组件com.ljx.gameview.GameView总是获得空指针
求各路前辈支援,解答

============解决方案1============


findViewByid是在Activity自己的window上查找的。。。

你有那个view的代码吗?

不行就自己动态在代码里创建view好了
原文地址:https://www.cnblogs.com/lianxu61/p/4038759.html