标签:管理 update ini src 抽象 text 技术 nts lan
转载于:
public abstract class BasePageFragment extends Fragment { protected boolean isViewInitiated; protected boolean isVisibleToUser; protected boolean isDataInitiated; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); isViewInitiated = true; prepareFetchData(); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); this.isVisibleToUser = isVisibleToUser; prepareFetchData(); } public abstract void fetchData(); public boolean prepareFetchData() { return prepareFetchData(false); } public boolean prepareFetchData(boolean forceUpdate) { if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) { fetchData(); isDataInitiated = true; return true; } return false; } }
public class PageFragment extends BasePageFragment { public static PageFragment newInstance(String title){ PageFragment fragment = new PageFragment(); Bundle args = new Bundle(); args.putString("key_fragment_title", title); fragment.setArguments(args); return fragment; } private String title; private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); title = getArguments().getString("key_fragment_title"); Trace.d(title + ":onCreate"); } @Override public void onResume() { super.onResume(); Trace.d(title + ":onResume"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Trace.d(title + ":onCreateView"); tv = new TextView(getActivity()); return tv; } @Override public void fetchData() { tv.setText(title); /** * 在这里请求网络。 */ } }
如果你也有这样的需求或者烦恼,保证药到病除。
有同学说实践过程中遇到了些问题,比如Fragment只刷新一次,这个问题只要手动调用prepareFetchData(),传true即可强制刷新了。还有同学质疑setUserVisibleHint()和onActivityCreated()的执行先后的问题。关于这个请看下图。
标签:管理 update ini src 抽象 text 技术 nts lan
原文地址:http://www.cnblogs.com/shijunzhang/p/7590396.html