BaseFragment基類的創建和子類的繼承
阿新 • • 發佈:2019-03-23
strac final private save 效果 state spa oncreate rri
一、創建基類 BaseFragment
package com.example.zhenghuajing.shoppingmall.base; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;/** * Created by zhenghuajing on 2019/3/23. * BaseFragment */ public abstract class BaseFragment extends Fragment { public Context mContext; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = getActivity(); } @Nullable @Overridepublic View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return initView(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initData(); }/** * 初始化數據 */ public void initData() { } /** * 由子類實現,實現特有效果 * @return */ public abstract View initView(); }
二、首頁HemoFragment繼承基類
package com.example.zhenghuajing.shoppingmall.home.fragment; import android.graphics.Color; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.TextView; import com.example.zhenghuajing.shoppingmall.base.BaseFragment; /** * Created by zhenghuajing on 2019/3/23. * 首頁 */ public class HomeFragment extends BaseFragment { private static final String TAG = HomeFragment.class.getSimpleName(); private TextView textView; @Override public View initView() { Log.e(TAG, "主頁被初始化"); textView = new TextView(mContext); textView.setGravity(Gravity.CENTER); textView.setTextSize(25); textView.setTextColor(Color.RED); return textView; } @Override public void initData() { super.initData(); Log.e(TAG, "主頁被初始化了"); textView.setText("主頁"); } }
BaseFragment基類的創建和子類的繼承