为什么findViewById()不能用作getActivity()。findViewById()在这里?

时间:2015-07-08 21:14:00

标签: java android android-activity

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_detail,
                    container, false);
            // The detail Activity called via intent.  Inspect the intent for forecast data.
            Intent intent=getActivity().getIntent();
            TextView text=(TextView)rootView.findViewById(R.id.text1);
            String b=intent.getStringExtra(Intent.EXTRA_TEXT);
            text.setText(b);

            return rootView;
        }
    }

在我使用

时的代码中
TextView text=(TextView)getActivity().findViewById(R.id.text1)

然后我的应用程序崩溃,Logcat说

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

这是与此代码相关联的XML文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sunshine.app.DetailActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

2 个答案:

答案 0 :(得分:3)

  

在此代码中,当我使用TextView text =(TextView)getActivity()。findViewById(R.id.text1)

     

然后我的应用程序崩溃并且Logcat说由引起:java.lang.NullPointerException:尝试调用虚方法&#39; android.view.View android.view.Window.findViewById(int)&#39;在空对象引用上

findViewById()上的Activity从根视图开始(所谓的&#34;装饰视图&#34;)并遍历可用小部件和容器的树,寻找ID匹配。因此,调用findViewById()的{​​{1}}只会查找属于整个活动视图层次结构的视图。

但是,您的Activity调用不会将夸大的inflate()附加到活动视图层次结构中。这是预料之中的。在从RelativeLayout返回后,在附加片段本身时,这些视图将附加到活动视图层次结构中。因此,当您从onCreateView() 内部的活动上致电findViewById()时,找不到您的onCreateView(),因为TextView只是{由片段管理,但尚未成为活动视图层次结构的一部分。

TextViewfindViewById()上的{p> ViewViewGroupView开始,遍历可用小部件和容器树,查找ID匹配。 ViewGroup可以访问您的RelativeLayout,因此当您在TextView上致电findViewById()时,它会正常运行。

答案 1 :(得分:0)

这是因为fragment_detail.xml布局包含TextView,标识为text1,而非活动布局。