Statistical由Activity改为Fragment

来源:互联网 发布:配乐朗诵的软件 编辑:程序博客网 时间:2024/05/19 13:25

在修改的过程中出现的问题:

1.private Activity activity = getActivity();写在全局中会出现NullPointException异常,

修改方法.private Activity activity在全局变量中声明,然后在方法体中赋值,如:

public void onCreate(Bundle savedInstanceState) {


activity = getActivity();
                ......
}

2.在向Activity中的Fragment传参时,控制台会报错,如下:
 1〉The method findViewById(int) is undefined for the type EventStatisticalComparisonFragment
 2>The method onCreateOptionsMenu(Menu, MenuInflater) in the type Fragment is not applicable for the arguments (Menu)
 解决方法:在其前面加getActivity()

3.Intent pumping_statistics = new Intent(EventStatisticalComparisonFragment.this,MilkCalculator.class);

Intent传参时会提示错误,

解决方法:

Intent pumping_statistics = new Intent(getActivity(),
MilkCalculator.class);


4.详细提示如下:
由于ADT版本问题,若打开layout时 如果提示:Incorrect line ending: found carriage return (\r) without corresponding newline (\n) 
解决方案: ——clean一下项目,这个方法可以解决 。

5.把原来的Activity改成Activity+Fragmrnt,,然后再EventStatisticalComparison.java文件中添加Fragment
           fragmentTransaction.add(R.layout.baby_eventinfo_statistics_fragment, fragment);
控制台报错:IllegalArgumentException!

错误原因:

fragmentTransaction.add()方法第一个参数是父容器布局文件的id,第二个参数是要放置的fragment文件名。所以不是直接R.layout.通过布局文件名来调用!

解决方法:

fragmentTransaction.add(R.id.baby_history_linear_layout, fragment);



6.solidTimesToday = (TextView) findViewById(R.id.feed_times_today);
控制台报错:The method findViewById(int) is undefined for the type EventStatisticalComparisonFragment
然后在其前面添加getActivity():
 solidTimesToday = (TextView) getActivity().findViewById(R.id.feed_times_today);
调试时仍抛异常:solidTimesToday 是NullPointException,

错误原因:

原来在EventStatisticalComparison.xml文件中的布局现在全部在EventStatisticalComparisonFragment.xml布局文件中,

getActivity()得到的是与该Fragment文件有联系的Activity,而原来的布局文件中已经没有这些控件了,所以是空指向
解决方法:
在OnCreateView()方法中得到EventStatisticalComparisonFragment.java的布局文件视图mThisFragmentView 
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mThisFragmentView = inflater.inflate(
R.layout.baby_eventinfo_statistics_fragment, container, false);
return mThisFragmentView;
}
然后:

  solidTimesToday = (TextView) mThisFragmentView.findViewById(R.id.feed_times_today);


心得:

1.在一个大的项目中有许多文件,要找的你需要的文件是首要的问题。第一步先要找与视图显示的标题有联系的字母,但要注意的是视图中的标题一般都是缩写,所以当你找不到与视图标题一样的名字时就找与他们相近的字母,这样就会很快找到了。

2.Eclipse的调试很好用,要勇于尝试。



原创粉丝点击