加载后刷新片段

时间:2014-05-19 22:11:01

标签: java android navigation fragment drawer

所以我最近进入了Android编程,有一段时间我一直在努力解决这个问题。我使用导航抽屉并附加了一些碎片。但每当我切换标签/片段时,所有变量都会重置,我必须再次手动重置它们。

但是,我想它是自动的。碎片加载后 - >刷新自定义类的数据..

这是我的片段代码,但它在nullpointerexception上崩溃。

public class TimeFragment extends Fragment {

        private final String ARG_SECTION_NUMBER = "section_number";

        public TimeFragment(int sectionNumber) {
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            this.setArguments(args);
        }

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


        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
            refreshFragment();
        }

        public void refreshFragment() {
            TextView text_first = (TextView) findViewById(R.id.textViewNS_Days);
            TextView text_second = (TextView) findViewById(R.id.textViewNS_Money);
            TextView text_third = (TextView) findViewById(R.id.textViewNS_Cigs);
            text_first.setText(String.format("%d", smokes.daysNotSmoked()));
            text_second.setText(String.format("%.1f", smokes.moneySaved()));
            text_third.setText(String.format("%d", smokes.cigsNotSmoked()));
        }

    }

这是设置片段的默认方法。

    @Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    Fragment fragment = new PlaceholderFragment(position + 1);
    switch (position) {
        case 0:
            fragment = new TimeFragment(position + 1);
            break;

    }
    fragmentManager.beginTransaction()

            .replace(R.id.container, fragment)
            .commit();

}

1 个答案:

答案 0 :(得分:1)

我发现我可以使用

@Override
public void onResume(){

}

片段。解决了它。