java - 加载后刷新Fragment

标签 java android navigation fragment drawer

所以我最近开始接触 Android 编程,有一段时间我一直在努力解决这个问题。我使用抽屉导航并附加了一些 fragment 。但是每当我切换选项卡/fragment 时,所有变量都会重置,我必须再次手动重置它们。

但是,我希望它是自动的。 fragment 加载后 -> 从自定义类刷新数据..

这是我的 fragment 代码,但它因空指针异常而崩溃。

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()));
        }

    }

这是设置 fragment 的默认方法。

    @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();

}

最佳答案

我发现我可以使用

@Override
public void onResume(){

}

关于 fragment 。解决了。​​

关于java - 加载后刷新Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23748024/

相关文章:

css - 有些导航链接有效,有些则无效。相对 URL 路径?

java - Spring Boot 2.0 中的 RedisCacheManager.setCacheNames

java - 如何为 Google Closure 制作插件

java - 使用 Smart GWT TreeGrid 进行导航

android - 线性布局 : How to position elements

java - 获取在 ListActivity 中单击的项目的信息?

css - 链接为类似按钮的外观

java - 在多实例环境中仅执行一次 Quartz 作业

java - 编写 java 游戏 - JFrame 未按预期工作

java - 无法在 Android 中获取并显示 JSON