Android 使用 Fragment 时 findViewById 返回 NULL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10469283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:51:05  来源:igfitidea点击:

findViewById returns NULL when using Fragment

androidandroid-activitynullreferenceexceptionfragment

提问by mammadalius

I'm new to Android developing and of course on Fragments.

我是 Android 开发的新手,当然还有 Fragments。

I want to access the controls of my fragment in main activity but 'findViewById' returns null. without fragment the code works fine.

我想在主要活动中访问我的片段的控件,但“findViewById”返回 null。没有片段代码工作正常。

Here's part of my code:

这是我的代码的一部分:

The fragment:

片段

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

    <EditText
        android:id="@+id/txtXML"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:ems="10"
        android:scrollbars="vertical">
    </EditText>

</LinearLayout>

the onCreate of MainActivity:

MainActivity 的 onCreate:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.main);

        this.initialisePaging();

        EditText txtXML = (EditText) findViewById(R.id.txtXML);}

on this point the txtXMLis null.

在这一点上,txtXML为空。

What's Missing in my code or what should I do?

我的代码中缺少什么或我应该怎么做?

采纳答案by mammadalius

You should inflatethe layout of the fragment on onCreateViewmethod of the Fragmentthen you can simply access it's elements with findViewByIdon your Activity.

你应该inflateonCreateView方法的片段布局Fragment然后你可以简单地访问它的元素findViewById在你的Activity.

In this Example my fragment layout is a LinearLayout so I Cast the inflateresult to LinearLayout.

在这个例子中,我的片段布局是一个 LinearLayout,所以我将inflate结果转换为 LinearLayout。

    public class FrgResults extends Fragment 
    {
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        {
            //some code
            LinearLayout ll = (LinearLayout)inflater.inflate(R.layout.frg_result, container, false);
            //some code
            return ll;
        }
    }

回答by Ufuk Doganca

Try like this on your fragments on onCreateView

在 onCreateView 上的片段上尝试这样

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (container == null) {
        return null;
    }

    LinearLayout ll = (LinearLayout )inflater.inflate(R.layout.tab_frag1_layout, container, false);
EditText txtXML = (EditText) ll.findViewById(R.id.txtXML);

    return ll;
}

回答by gdi

I'm late, but for anyone else having this issue. You should be inflating your view in the onCreateView method. Then override the onCreateActivitymethod and you can use getView().findViewByIdthere.

我迟到了,但对于其他遇到此问题的人。您应该在 onCreateView 方法中扩充您的视图。然后覆盖该onCreateActivity方法,您可以getView().findViewById在那里使用。

@Override public View onCreateView(LayoutInflater inflater, ViewGroup     container, Bundle savedInstanceState) 
{
     return      inflater.inflate(R.layout.fragment, container, false);
}

回答by Nixit Patel

You can't access the the view of fragment in activity class by findViewByIdinstead what you can do is...

您无法访问活动类中的片段视图,findViewById而您可以做的是......

You must have an object of Fragment class in you activity file, right? create getter method of EditText class in that fragment class and access that method in your activity.

您的活动文件中必须有 Fragment 类的对象,对吗?在该片段类中创建 EditText 类的 getter 方法并在您的活动中访问该方法。

create a call back in Fragment class on the event where you need the Edittext obj.

在需要 Edittext obj 的事件上在 Fragment 类中创建回调。

回答by Bobs

1) Try this:

1)试试这个:

Eclipse menu -> Project -> Clean...

Eclipse 菜单 -> 项目 -> 清理...

update

更新

2) If you have 2 or more instances of 'main' layout, check if all of them have a view with 'txtXML' id

2) 如果你有 2 个或更多的 'main' 布局实例,检查它们是否都有一个带有 'txtXML' id 的视图

3)

3)

A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity. Interaction with fragments is done through FragmentManager, which can be obtained via Activity.getFragmentManager() and Fragment.getFragmentManager().

Fragment 是可以放置在 Activity 中的应用程序用户界面或行为的一部分。与片段的交互是通过 FragmentManager 完成的,可以通过 Activity.getFragmentManager() 和 Fragment.getFragmentManager() 获取。

The Fragment class can be used many ways to achieve a wide variety of results. It is core, it represents a particular operation or interface that is running within a larger Activity. A Fragment is closely tied to the Activity it is in, and can not be used apart from one. Though Fragment defines its own lifecycle, that lifecycle is dependent on its activity: if the activity is stopped, no fragments inside of it can be started; when the activity is destroyed, all fragments will be destroyed.

Fragment 类可以通过多种方式来实现各种各样的结果。它是核心,它代表在更大的 Activity 中运行的特定操作或接口。Fragment 与它所在的 Activity 密切相关,不能单独使用。尽管 Fragment 定义了自己的生命周期,但该生命周期取决于其 Activity:如果 Activity 停止,则其内部的任何 Fragment 都无法启动;当activity被销毁时,所有的fragment都会被销毁。

Study this. you must use FragmentManager.

研究这个。您必须使用 FragmentManager。

回答by Moesio

If you want use findViewById as you use at activities onCreate, you can simply put all in overrided method onActivityCreated.

如果您想在活动 onCreate 中使用 findViewById,您可以简单地将所有内容放在覆盖方法 onActivityCreated 中。