手撸一个BaseActivity和BaseFragment
为了方便,我们抽离公共方法,提供基类接口:
/**
* 基类公共接口
* Created by Chao on 2017-12-23.
*/
public interface BaseInterFace {
/**
* 子类布局
*/
int getLayout();
/**
* 初始化View
*/
void initView();
/**
* 初始化数据
*/
void initData();
/**
* 初始化监听
*/
void initListener();
}
BastActivity和BaseFragment实现该接口
/**
* Activity基类
* Created by Chao on 2017-12-23.
*/
public abstract class BaseActivity extends AppCompatActivity implements BaseInterFace {
protected Context mContext;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(getLayout());
init();
}
private void init() {
initView();
initData();
initListener();
}
@Override
public void initView() {
}
@Override
public void initData() {
}
@Override
public void initListener() {
}
}
/**
* Fragment基类
* Created by Chao on 2017-12-23.
*/
public abstract class BaseFragment extends Fragment implements BaseInterFace {
protected View rootView;
protected Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(getLayout(), container, false);
init();
return rootView;
}
private void init() {
initView();
initData();
initListener();
}
@Override
public void initView() {
}
@Override
public void initData() {
}
@Override
public void initListener() {
}
}
测试,在我们的项目继承我们刚才写的基类:
测试通过,下篇写一个自定义注解吧,butterknife也是同理,不过这里扩展一下吧。
源码地址:https://github.com/zhangzhichaolove/BasicsFrame