繁体   English   中英

findViewById在运行方法中返回null(android)

[英]findViewById is returning null inside run method (android)

由于某种原因,这里的run方法可以轻松设置内容视图,但是当我尝试从xml中检索按钮时,它将返回null,并且不允许我设置onclick侦听器。 我的代码在下面列出。

v.post(new Runnable() {
    @Override
    public void run() {
        setContentView(R.layout.win);
        Button submit = (Button) findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                HighScoresHelper scores = new HighScoresHelper("HighScoreV2.txt", GameActivity.this);
                scores.addScore("Test", Math.round((frame/FPS) *100)/100.0);
                startActivity(new Intent(GameActivity.this, HighScores.class));
                finish();
            }
        });
    }
});

是的,拼写和所有内容都正确并且与xml匹配,这是xml代码

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

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="YOU WON!!!, enter in your name and click submit"
    android:id="@+id/textView3" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/name" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Submit"
    android:id="@+id/submit"
    android:layout_gravity="center_horizontal" />
 </LinearLayout>

谢谢

因此,问题在于我在活动的内部类内部调用了此方法。 我需要做的是扩大视图并将其另存为全局变量。 我在onCreate方法中完成了所有这些工作。

  LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            winView = inflater.inflate(R.layout.win, null);
            submit = (Button) winView.findViewById(R.id.submitScore);

            submit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

然后在我的内心课堂里,我打电话给

v.post(new Runnable() {
                    @Override
                    public void run() {
                        setContentView(winView);
                    }
                });

为了在必要时更改视图,v是主类的内部类实例变量。

为了澄清起见,主类“ GameActivity”和内部类被标记为“ OurView”。 v是类GameActivity中的OurView类型的全局变量。 我会发布整个课程,但其长度超过300行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM