findViewById返回null

时间:2012-09-24 19:46:28

标签: android viewgroup findviewbyid

我正在使用像Facebook这样的滑动菜单构建Android应用,但ViewGroup无效。它在运行4.1的手机上运行正常但当我尝试在运行2.3的模拟器上运行我的代码时,mContent = (FrameLayout) findViewById(R.id.animation_layout_content);此行总是返回null;但是,mSidebar正确返回视图。如果有人帮助解决这个问题我真的很感激。谢谢!

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_singlepane_empty);

    if (getIntent().hasExtra(Intent.EXTRA_TITLE)) {
        setTitle(getIntent().getStringExtra(Intent.EXTRA_TITLE));
    }

    final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE);
    setTitle(customTitle != null ? customTitle : getTitle());

    if (savedInstanceState == null) {
        mFragment = onCreatePane();
        mFragment.setArguments(intentToFragmentArguments(getIntent()));
        getSupportFragmentManager().beginTransaction()
                .add(R.id.animation_layout_content, mFragment, "single_pane")
                .commit();
    } else {
        mFragment = getSupportFragmentManager().findFragmentByTag("single_pane");
    }

    mLayout = (AnimationLayout) findViewById(R.id.animation_layout);
    mLayout.setListener(this);
}


layout.activity_singlepane_empty
<com.oldroid.apps.planit.util.AnimationLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/animation_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<include layout="@layout/menu_sidebar" />

<FrameLayout
    android:id="@id/animation_layout_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

 AnimationLayout
 @Override
public void onFinishInflate() {
    super.onFinishInflate();
    mContent = (FrameLayout) findViewById(R.id.animation_layout_content);
    mSidebar = findViewById(R.id.animation_layout_sidebar);

    if (mSidebar == null) {
        throw new NullPointerException("no view id = animation_sidebar");
    }

    if (mContent == null) {
        throw new NullPointerException("no view id = animation_content");
    }

    mOpenListener = new OpenListener(mSidebar, mContent);
    mCloseListener = new CloseListener(mSidebar, mContent);
}

1 个答案:

答案 0 :(得分:4)

变化:

android:id="@id/animation_layout_content"

为:

android:id="@+id/animation_layout_content"

也就是说,除非您在其他地方(在资源xml文件中添加了ID)。有关@id vs @+id

的详细信息,请参阅this thread