這兩天看了黑馬程序員“新聞”項目,覺得BaseFragment寫法不錯。所以來貼代碼的。
BaseFragment.java
<span style="font-size:14px;">package com.heima.news.base;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.heima.news.MainActivity;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
public abstract class BaseFragment extends Fragment {
public View view;
public Context ct;
public SlidingMenu sm;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initData(savedInstanceState);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ct = getActivity();
sm = ((MainActivity) getActivity()).getSlidingMenu();
}
/**
* setContentView;
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = initView(inflater);
return view;
}
public View getRootView() {
return view;
}
/**
* 初始化view
*/
public abstract View initView(LayoutInflater inflater);
/**
* 初始化數據
*/
public abstract void initData(Bundle savedInstanceState);
}
</span>
子類:
<span style="font-size:14px;">package com.heima.news.fragment;
public class HomeFragment extends BaseFragment {
@Override
public View initView(LayoutInflater inflater) {
view = inflater.inflate(R.layout.frag_home2, null);
<span style="white-space:pre"> </span>.......
return view;
}
List<BasePage> list = new ArrayList<BasePage>();;
@Override
public void initData(Bundle savedInstanceState) {
.......
}
}
</span>
子類實現了父類的抽象方法,省去了每次需要Override那幾個生命週期方法,代碼看起來更簡潔。
新聞項目的下載鏈接:http://download.csdn.net/detail/yersterday/7900977
(需要說明的是代碼只含有導航功能,沒有具體模塊的實現)。
下面Activity基類的代碼是另一個項目的:
package com.immomo.momo.android;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import com.immomo.momo.android.dialog.FlippingLoadingDialog;
import com.immomo.momo.android.util.NetWorkUtils;
import com.immomo.momo.android.view.HandyTextView;
public abstract class BaseActivity extends FragmentActivity {
// protected BaseApplication mApplication;
// protected NetWorkUtils mNetWorkUtils;
// protected FlippingLoadingDialog mLoadingDialog;
/**
* 屏幕的寬度、高度、密度
*/
protected int mScreenWidth;
protected int mScreenHeight;
protected float mDensity;
protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// mApplication = (BaseApplication) getApplication();
// mNetWorkUtils = new NetWorkUtils(this);
// mLoadingDialog = new FlippingLoadingDialog(this, "請求提交中");
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
mScreenWidth = metric.widthPixels;
mScreenHeight = metric.heightPixels;
mDensity = metric.density;
}
@Override
protected void onDestroy() {
clearAsyncTask();
super.onDestroy();
}
/** 初始化視圖 **/
protected abstract void initViews();
/** 初始化事件 **/
protected abstract void initEvents();
protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
mAsyncTasks.add(asyncTask.execute());
}
protected void clearAsyncTask() {
Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
.iterator();
while (iterator.hasNext()) {
AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
if (asyncTask != null && !asyncTask.isCancelled()) {
asyncTask.cancel(true);
}
}
mAsyncTasks.clear();
}
// protected void showLoadingDialog(String text) {
// if (text != null) {
// mLoadingDialog.setText(text);
// }
// mLoadingDialog.show();
// }
// protected void dismissLoadingDialog() {
// if (mLoadingDialog.isShowing()) {
// mLoadingDialog.dismiss();
// }
// }
/** 短暫顯示Toast提示(來自res) **/
protected void showShortToast(int resId) {
Toast.makeText(this, getString(resId), Toast.LENGTH_SHORT).show();
}
/** 短暫顯示Toast提示(來自String) **/
protected void showShortToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
/** 長時間顯示Toast提示(來自res) **/
protected void showLongToast(int resId) {
Toast.makeText(this, getString(resId), Toast.LENGTH_LONG).show();
}
/** 長時間顯示Toast提示(來自String) **/
protected void showLongToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
/** 顯示自定義Toast提示(來自res) **/
protected void showCustomToast(int resId) {
View toastRoot = LayoutInflater.from(BaseActivity.this).inflate(
R.layout.common_toast, null);
((HandyTextView) toastRoot.findViewById(R.id.toast_text))
.setText(getString(resId));
Toast toast = new Toast(BaseActivity.this);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastRoot);
toast.show();
}
/** 顯示自定義Toast提示(來自String) **/
protected void showCustomToast(String text) {
View toastRoot = LayoutInflater.from(BaseActivity.this).inflate(
R.layout.common_toast, null);
((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
Toast toast = new Toast(BaseActivity.this);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastRoot);
toast.show();
}
/** Debug輸出Log日誌 **/
protected void showLogDebug(String tag, String msg) {
Log.d(tag, msg);
}
/** Error輸出Log日誌 **/
protected void showLogError(String tag, String msg) {
Log.e(tag, msg);
}
/** 通過Class跳轉界面 **/
protected void startActivity(Class<?> cls) {
startActivity(cls, null);
}
/** 含有Bundle通過Class跳轉界面 **/
protected void startActivity(Class<?> cls, Bundle bundle) {
Intent intent = new Intent();
intent.setClass(this, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivity(intent);
}
/** 通過Action跳轉界面 **/
protected void startActivity(String action) {
startActivity(action, null);
}
/** 含有Bundle通過Action跳轉界面 **/
protected void startActivity(String action, Bundle bundle) {
Intent intent = new Intent();
intent.setAction(action);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivity(intent);
}
/** 含有標題和內容的對話框 **/
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 positiveText,
DialogInterface.OnClickListener onPositiveClickListener,
String negativeText,
DialogInterface.OnClickListener onNegativeClickListener) {
AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle(title)
.setMessage(message)
.setPositiveButton(positiveText, onPositiveClickListener)
.setNegativeButton(negativeText, onNegativeClickListener)
.show();
return alertDialog;
}
/** 含有標題、內容、圖標、兩個按鈕的對話框 **/
protected AlertDialog showAlertDialog(String title, String message,
int icon, String positiveText,
DialogInterface.OnClickListener onPositiveClickListener,
String negativeText,
DialogInterface.OnClickListener onNegativeClickListener) {
AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle(title)
.setMessage(message).setIcon(icon)
.setPositiveButton(positiveText, onPositiveClickListener)
.setNegativeButton(negativeText, onNegativeClickListener)
.show();
return alertDialog;
}
/** 默認退出 **/
protected void defaultFinish() {
super.finish();
}
}