Android基础——构建自己喜欢的BaseActivity、BaseFragment抽象类

BaseActvity

所有Activity的基类,可以提高代码的阅读性和简洁性,根据你个人喜爱构建出自己的抽象类吧

可以在BaseActivity中放置一些第三方服务的初始化代码和网络监听事件等等等

步骤一:创建BaseActivity抽象类:

public abstract class BaseActivity extends FragmentActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initViews();
        initListener();
        initData();
    }

    public abstract void initViews();

    public abstract void initListener();

    public abstract void initData();

    public abstract void processClick(View v);

    public void onClick(View v) {
        processClick(v);
    }

}
步骤二:在代码中的使用:

public class MyActivity extends BaseActivity {

    @Override
    public void initViews() {
        //放置初始化View
        setContentView(R.layout.activity_my);
    }

    @Override
    public void initListener() {
        //放置控件的监听事件
    }

    @Override
    public void initData() {
        //放置初始化数据
    }

    @Override
    public void processClick(View v) {
        //处理控件的监听事件
    }
}

BaseFragment

步骤一:创建BaseFragment抽象类:

public abstract class BaseFragment extends Fragment implements View.OnClickListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return initViews(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        initListener();
    }

    public abstract View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

    public abstract void initData();

    public abstract void initListener();

    public abstract void processClick(View v);

    @Override
    public void onClick(View v) {
        processClick(v);
    }
}
步骤二:在代码中的使用:

public class MineFragment extends BaseFragment {

    @Override
    public View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, null);
        return view;
    }

    @Override
    public void initData() {
    }

    @Override
    public void initListener() {

    }

    @Override
    public void processClick(View v) {

    }
}




你可能感兴趣的:(java,android,抽象类,Activity,Fragment)