2016-02-05 70 views
0

此代码:Android应用程序编程 - 不知道为什么findViewByID执行以下操作:

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); 
     Intent intent = getActivity().getIntent(); 
     String weather = intent.getStringExtra(Intent.EXTRA_TEXT); 
     if(weather != null) { 
      TextView textViewWeather=(TextView)rootView.findViewById(R.id.weatherText); 
      textViewWeather.setText(weather); 

,但如果你更换,在该行

(TextView)rootView.findViewById(R.id.weatherText);

rootView通过findView()getActivity,它返回null,所以下一行创建一个运行时间致命错误,它会暂停程序。

我不明白为什么。我认为背景是活动?!我很困惑,并且无法通过android开发人员找到一个好的答案,所以我在这里...

在此先感谢谁帮助!

+0

你可以发布xml吗? –

回答

0

该行从rootView中获取ID为weatherText的元素。这不过是你的片段xml文件

TextView textViewWeather=(TextView)rootView.findViewById(R.id.weatherText); 


现在,如果你用下面

TextView textViewWeather=(TextView)getActivity().findViewById(R.id.weatherText); 

现在在这个片段托管父活动具有TextView和ID替换上述代码将按框架搜索weatherText

这是显而易见的根本不存在。

0

如果您删除了rootView,则您直接在activity上调用它,因此这两个建议是相同的(活动实际上是context)。

但是这个活动并不知道布局,你只是从xml中夸大它,但它还没有被赋予活动,因此无法找到。您可以通过从示例代码中的onCreateView调用中返回它来完成此操作。

1

,当你拨打:

View rootView = inflater.inflate(R.layout.fragment_detail, container, false); 
TextView textViewWeather=(TextView)rootView.findViewById(R.id.weatherText); 

rootView现在包含在fargment_detail.xml中定义的看法。 和weatherText就是其中之一。

但当你叫getActivity()。findViewById()findViewById()要找到weatherText活动的XML文件中并没有weatherText有那么它将retun

相关问题