Java 自定义视图中我的文本视图存在问题

Java 自定义视图中我的文本视图存在问题,java,android,layout,textview,Java,Android,Layout,Textview,在任何人开口之前,我知道以前有人问过这类问题,我已经看了很多关于这方面的问题,但没有找到任何有帮助的 在我的自定义视图中,我试图在布局文件中找到一个始终返回null的textview 这是我的密码: Main.java public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(saved

在任何人开口之前,我知道以前有人问过这类问题,我已经看了很多关于这方面的问题,但没有找到任何有帮助的

在我的自定义视图中,我试图在布局文件中找到一个始终返回null的textview

这是我的密码:

Main.java

public class Main extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.game );
    }
.....
CustomView.java

public class CustomView extends SurfaceView
{
    TextView MyTextView; // <-- THIS SHOULD BE SET    

    public CustomView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }
公共类CustomView扩展了SurfaceView
{

TextView MyTextView;//假设您已将布局文件中
TextView
id
设置为
TextView 1
只需按如下方式分配:

MyTextView=(TextView)findViewById(R.id.TextView1);


但您需要在自定义视图中添加或膨胀布局。

仅在视图组中引用视图不会将其添加到视图层次结构中。您需要调用addView(或其关联方法之一)-然后,该视图将包含在子视图列表中,并将成为onMeasure、onLayout流程等的一部分


findViewById递归地在视图层次结构中查找id,因此该视图需要位于要查找的子视图组列表中

是的,我忘记了演员阵容。稍后将添加它。这不起作用,返回时出现NULL异常。请记住,我试图在GameView中而不是在Main中查找该视图。您将GameView与哪个位置关联包含具有该ID的TextView的XML文件?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gamelayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/background">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_gravity="center"
        android:orientation="horizontal"
        android:layout_weight="0.025">

        <TextView
            android:id="@+id/MyTextView" // This needs to be found
            android:layout_width="0dip"
            android:layout_weight="1"
            android:textSize="16sp"
            android:text="@string/health"
            android:layout_height="fill_parent"
            android:contentDescription="@string/health"/>

    </LinearLayout>

    <package.CustomView
                ....... />

</LinearLayout>