1.新建BaseActivity继承FragmenytActivity。由于我习惯在Activity里用些公共的方法,所以将此类建为abstract
public abstract class BaseActivity extends FragmentActivity { }
2.重写onCreate()方法
public abstract class BaseActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base_activity); } }
3.编写必要的属性
public abstract class BaseActivity extends FragmentActivity { protected int mScreenWidth; protected int mScreenHeight; protected float mDensity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_base_activity); DisplayMetrics metrics =new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); mScreenHeight = metrics.heightPixels; mScreenWidth = metrics.widthPixels; mDensity = metrics.density; } }
4.编写子类公共的方法
protected void showShortToast(int resId){ Toast.makeText(this, getString(resId), Toast.LENGTH_SHORT).show(); } protected void showShortToast(String text){ Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); } protected void showLongToast(int resId){ Toast.makeText(this, getString(resId), Toast.LENGTH_LONG).show(); } protected void showLongToast(String text){ Toast.makeText(this, text, Toast.LENGTH_LONG).show(); } protected void showLogDebug(String tag,String msg){ Log.d(tag, msg); } protected void showLogError(String tag,String msg){ Log.e(tag, msg); } protected void startActivity(Class<?> cls, Bundle bundle){ Intent intent = new Intent(); intent.setClass(this, cls); if(bundle != null){ intent.putExtras(bundle); } startActivity(intent); } protected void startActivity(Class<?> cls){ startActivity(cls,null); } protected AlertDialog showAlertDialog(String title,String message){ AlertDialog alertDialog = new AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .show(); return alertDialog; } protected AlertDialog showAlertDialog(String title,String message ,String posistiveText ,DialogInterface.OnClickListener onPositiveClickListener ,String negativeText ,DialogInterface.OnClickListener onNegativeClickListener){ AlertDialog alertDialog = new AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setPositiveButton(posistiveText, onPositiveClickListener) .setNegativeButton(negativeText, onNegativeClickListener) .show(); return alertDialog; } protected void defaultFinish(){ super.finish(); } abstract void initView(); abstract void initEvent();
时间: 2024-11-09 10:44:05