抽取基类——Activity和Fragment的基类抽取

本文探讨了在Android开发中如何进行Activity和Fragment的基类抽象,旨在提高代码复用性和组织性,降低维护成本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看看Activity的基类抽取

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.View;

/**
 * @Auther: 殒命星
 * @Date: 2019/1/19 10:33:${}
 * @Description:
 */
public abstract class BaseActivity extends FragmentActivity {//继承这个地方可以继承Activity也可以继承FragmentActivity

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(bindLayout());
        
        initView();
        initData();
        bindEvent();
    }
    protected abstract int bindLayout();
    protected abstract void initView();
    protected abstract void initData();
    protected abstract void bindEvent();
    protected <T extends View> T bindView(int resId){
        return (T) findViewById(resId);
    }
}

Fragment的基类抽取

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * @Auther: 殒命星
 * @Date: 2019/1/19 11:36:${}
 * @Description:
 */
public abstract class BaseFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(bindLayout(), container, false);

    }

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

    //绑定xml
    protected abstract int bindLayout();
    //获取控件
    protected abstract void initView();
    //操作数据
    protected abstract void initData();
    //监听
    protected abstract void bindEvent();
    //找控件
    protected <T extends View> T bindView(int resId){
        return (T) getView().findViewById(resId);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值