繁体   English   中英

(FrameLayout)findViewById(...)给出null

[英](FrameLayout)findViewById(…) gives null

我是android的新手,非常感谢任何帮助。 我试图使用背景作为我的视图,并假设我想创建一个简单的Credits页面,其中包含以下文件:credits.xml Credits.java

Credits.java:

public class Credits extends Activity implements OnTouchListener
{   
    private FrameLayout fl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            fl = (FrameLayout)findViewById(R.id.credits_screen);
            if ( fl == null ) Log.e("Credits", "fl is null");
            else {
                  fl.setOnTouchListener(this);
                  setContentView(fl);
            }
    }
    @Override 
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }
}

在我的credits.xml中,我有:

<?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"
 android:focusable="true" android:id="@+id/credits_screen">

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:src="@drawable/credits" android:scaleType="fitXY" />

</FrameLayout>

显然,fl在(FrameLayout)findViewById()处返回null。 虽然我看到R.id.credits_screen是在R文件中生成的。 我可以知道我的代码有什么问题吗? 为什么它无法找到FrameLayout?

您需要在findViewById()之前调用setContentView()。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.credits);
    fl = (FrameLayout) findViewById(R.id.credits_screen);
    fl.setOnTouchListener(this);
}

暂无
暂无

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

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