android - findViewById 返回 null

标签 android viewgroup findviewbyid

我正在使用类似 Facebook 的滑动菜单构建 Android 应用程序,但 ViewGroup 无法正常工作。它在我运行 4.1 的手机上运行良好,但是当我尝试在运行 2.3 的模拟器上运行我的代码时,mContent = (FrameLayout) findViewById(R.id.animation_layout_content); 此行总是返回 null ;但是,mSidebar 会正确返回 View 。如果有人帮助解决这个问题,我将不胜感激。谢谢你!

    @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);
}

最佳答案

改变:

android:id="@id/animation_layout_content"

到:

android:id="@+id/animation_layout_content"

也就是说,除非您在别处添加了 ID(在资源 xml 文件中,或其他地方)。参见 this thread有关 @id@+id 的详细信息。

关于android - findViewById 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12571844/

相关文章:

java - 尝试在模板 xml 文件的循环中以编程方式设置 View

java - Android findViewById 找不到资源

java - 在外部类中使用 findViewById

android - 在 Android Studio 中生成 .so 文件

java - AlertDialog 不显示在 android studio 中

c# - 移动跨平台游戏开发的最佳编程语言

android - 自定义 ViewGroup 是否有可能使其布局为 "deflate"并膨胀另一个?

android - 复合控制转发状态

java - 使用 findViewById 设置 Fragment 类中 Textview 上的 Bundle 中的文本时出现 NullPointerException

android - 将 ViewPager 与不带 actionBar 的选项卡一起使用