简单抽取Base类

BaseActivity

public  abstract class BaseActivity extends AppCompatActivity {


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

        //设置内容视图
        setContentView(getLayout());

        initView();

        setListener();

        initData();


    }

    //获取布局的id
    public  abstract int getLayout();

    //查找页面上所有的组件
    public abstract void initView();

    //设置监听事件
    public abstract void setListener();

    //初使化数据
    public abstract void initData();









}

BaseFragment

public   abstract  class BaseFragment extends Fragment {

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

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

        initData();



    }

    //得到fragment的视图
    public abstract View getFragmentLayout(LayoutInflater inflater,ViewGroup container);

    //初使化数据
    public abstract void initData();

    //设置监听
    public abstract  void  setListener();


}

MainActivity

public class MainActivity extends BaseActivity {


    private TextView textView;
    private List  datas;

    //返回此activity对应的布局
    @Override
    public int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        //一般写 findviewbyid的代码
        textView = (TextView) findViewById(R.id.tv);


    }

    @Override
    public void setListener() {

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //调用父类的方法
                getToast("haha");

            }
        });

    }

    @Override
    public void initData() {

        datas=new ArrayList<>();
        datas.add("1111");

        //请求网络下载数据

        //动态添加fragment
        getSupportFragmentManager().beginTransaction().replace(R.id.lin,new NewsFragment()).commit();


    }
}

NewsFragment

public class NewsFragment extends BaseFragment {
    //返回当前fragmetn对应的视图
    @Override
    public View getFragmentLayout(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.item,container,false);
    }

    @Override
    public void initData() {
        Log.d("zzz","newsfragment:initData");


    }
}

你可能感兴趣的:(Android,开发)