所以我最近开始接触 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/