我有片段的主要活动,当我在其他活动中回到此活动时,此片段中的我的视图为空。当我进入MainActivity并调用onCreate()时,为什么不再调用onCreateView()?我想在每次回到这个活动时对片段进行一些更改,我该怎么做?
片段:
private View v;
private TextView info;
public MyFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_sun, container, false);
return v;
}
private void setFields(){
info= v.findViewById(R.id.infoText); //View is null here when I comeback to MainActivity
}
public void calculateWeather(double longitude, double latitude){
setFields();
//do sth
}
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
if(intent != null){
String response = intent.getStringExtra("SETTINGS_BACK");//to detect back to this activity
if(response != null){
refreshView();
}
}
private void setViewPager(){
viewPager = findViewById(R.id.viewpager);
adapter = new PagerAdapter(getSupportFragmentManager(), 2);
adapter.addFragment(new SunFragment(), "Sun");
tableLayout = findViewById(R.id.tabLayout);
if(viewPager != null) {
viewPager.setAdapter(adapter);
Fragment f = adapter.getItem(0);
sunFragment = (SunFragment)f;
}
if(tableLayout != null){
tableLayout.setupWithViewPager(viewPager);
}
}
private void refreshView(){
if(viewPager != null) {
sunFragment.calculateWeather(lon, lat);
}
PagerAdapter
public class PagerAdapter extends FragmentStatePagerAdapter {
private int fragmentNumber;
private List<Fragment> fragmentList = new ArrayList<>();
private List<String> fragmentsNameList = new ArrayList<>();
public PagerAdapter(FragmentManager fm, int fragmentNumber){
super(fm);
this.fragmentNumber = fragmentNumber;
}
public void addFragment(Fragment fragment, String name){
fragmentList.add(fragment);
fragmentsNameList.add(name);
}
public SunFragment getSunFragment(){
return (SunFragment)fragmentList.get(0);
}
@Override
public Fragment getItem(int position) {
if(position == 0){
return SunFragment.newInstance();
}
}
@Override
public int getCount() {
return fragmentNumber;
}
@Override
public CharSequence getPageTitle(int position) {
return fragmentsNameList.get(position);
}
}
//编辑:添加剩余代码
答案 0 :(得分:0)
在以下情况下,您的片段视图将被销毁:
1)附加活动被系统或用户杀死。
2)你自己在上面调用detach或者在它附加到的同一个父视图id上调用一个新片段的替换
3)您的片段超出了viewpager的屏幕外页面限制。默认是任何一方保持活着的1个片段。超过它时,不在窗口中的碎片会被破坏。同样,只要片段落入此窗口,它们就会被创建。
由于您的案例中没有任何内容指向上述任何内容,因此系统再次创建视图毫无意义
但是你可以听onResume中的更改,因为当从另一个活动回来后活动被取消暂停时它肯定会被调用。