ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
***** **基类封装概述** [TOC=6] ## 1 为什么要抽取基类? ## 1 我们目前学习到的知识哪些可以抽取基类? ## 1 如何抽取 抽取BaseActivity ~~~ public abstract class BaseActivity extends Activity { /***是否显示标题栏*/ private boolean isshowtitle = true; /***是否显示状态栏*/ private boolean isshowstate = true; /***封装toast对象**/ private static Toast toast; /***获取TAG的activity名称**/ protected final String TAG = this.getClass().getSimpleName(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(!isshowtitle){ requestWindowFeature(Window.FEATURE_NO_TITLE); } if(isshowstate){ getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN); } //设置布局 setContentView(initLayout()); //初始化控件 initView(); //设置数据 initData(); } /** * 设置布局 * * @return */ public abstract int initLayout(); /** * 初始化布局 */ public abstract void initView(); /** * 设置数据 */ public abstract void initData(); /** * 是否设置标题栏 * * @return */ public void setTitle(boolean ishow) { isshowtitle=ishow; } /** * 设置是否显示状态栏 * @param ishow */ public void setState(boolean ishow) { isshowstate=ishow; } /** * 显示长toast * @param msg */ public void toastLong(String msg){ if (null == toast) { toast = new Toast(this); toast.setDuration(Toast.LENGTH_LONG); toast.setText(msg); toast.show(); } else { toast.setText(msg); toast.show(); } } /** * 显示短toast * @param msg */ public void toastShort(String msg){ if (null == toast) { toast = new Toast(this); toast.setDuration(Toast.LENGTH_SHORT); toast.setText(msg); toast.show(); } else { toast.setText(msg); toast.show(); } } } ~~~ 抽取BaseFragment ~~~ public abstract class BaseFragment extends Fragment { protected BaseActivity mActivity; protected abstract int setView(); protected abstract void init(View view); protected abstract void initData(Bundle savedInstanceState); @Override public void onAttach(Activity activity) { super.onAttach(activity); mActivity = (BaseActivity) activity; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(setView(), container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); init(view); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initData(savedInstanceState); } } ~~~