关闭

Android 开发之基类(一)

标签: android
1151人阅读 评论(0) 收藏 举报
分类:

不说太多,直接上代码,不懂再说,只是一些零碎代码做个记录,各位看官看得懂,我深表荣幸,看不懂我也没法。


import com.huianrong.app.widget.toast.HuiToast;

/**
 * Created by LanYan on 2015/11/17.
 */
public interface OnBaseListener {

    /**
     * Code set theme related properties, such as: remove the title bar, full screen mode.
       Simple:
     *       //设置无标题
     *      requestWindowFeature(Window.FEATURE_NO_TITLE);
     *       //设置全屏
     *      getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
     *      WindowManager.LayoutParams.FLAG_FULLSCREEN);
     *      代码设置主题相关属性,比如:去掉标题栏,全屏模式等。
     */
    void applyTheme();

    /**
     * When the activity call the setContentView (int layout) method, this method is called to return to the layout
     * 当activity 调用setContentView(int layout) 方法时,调用此方法返回Layout
     * @return R.layout.xx
     */
    int setContentViewId();

    /**
     *  initialization operation
     */
    void initiazed();

    /**
     * 短时间的提示
     * Tips for a short period of time
     * @param content
     */
    void shortToast(String content);

    /**
     * 长时间的提示
     * Tips for a long period of time
     * @param content
     */
    void longToast(String content);

}

每个Activity需要涉及到的调用方法,下面是FragmentActivity基类(基于Xutils的注解):


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Toast;

import com.huianrong.app.HuiApplication;
import com.huianrong.app.Interfaces.OnBaseListener;
import com.huianrong.app.helper.FragmentHelper;
import com.huianrong.app.widget.toast.HuiToast;
import com.lidroid.xutils.ViewUtils;

import java.util.ArrayList;

/**
 * Created by LanYan on 2015/11/17.
 */
public abstract class BaseFragmentActivity extends FragmentActivity implements OnBaseListener {

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        applyTheme();
        setContentView(setContentViewId());
        ViewUtils.inject(this);
        HuiApplication.getInstance().addActivity(this);
        initiazed();

    }

    @Override
    public void applyTheme() {

    }

    @Override
    public void initiazed() {

    }

     @Override
     public void shortToast(String content) {
       /*********ToastHelper略***********/
    }

    @Override
    public void longToast(String content) {
       /*********ToastHelper略***********/
    }

    /**
     * 显示指定的Fragment
     * According to the specified fragments
     *
     * @param framLayoutId
     * @param cls
     * @param <T>
     */
    public <T extends Fragment> void replaceFragment(int framLayoutId, Class<T> cls) {
        FragmentHelper.getInstance().replaceFragment(this, framLayoutId, cls);
    }

    /**
     * 显示指定的Fragment
     * According to the specified fragments
     *
     * @param framLayoutId
     * @param cls
     * @param tag
     * @param <T>
     */
    public <T extends Fragment> void replaceFragment(int framLayoutId, Class<T> cls, String tag) {

        FragmentHelper.getInstance().replaceFragment(this, framLayoutId, cls, null);
    }

    /**
     *添加Fragment集合并返回Fragment集合
     * Add fragments set and return fragments
     * @param framLayoutId
     * @param clsList
     * @param <T>
     * @return
     */
    public <T extends Fragment> ArrayList<Fragment> addFragmentList(int framLayoutId, Class<T>[] clsList) {
        return FragmentHelper.getInstance().addFragmentList(this,framLayoutId, clsList);
    }

    /**
     *添加Fragment集合并返回Fragment集合
     * Add fragments set and return fragments
     * @param framLayoutId
     * @param clsList
     * @param tag
     * @param <T>
     * @return
     */
    public <T extends Fragment> ArrayList<Fragment> addFragmentList(int framLayoutId, Class<T>[] clsList, String tag) {

        return FragmentHelper.getInstance().addFragmentList(this,framLayoutId, clsList, null);
    }

    /**
     * 显示指定的Fragment
     * According to the specified fragments
     */
    public <T extends Fragment> void showFragment(int framLayoutId, int position, ArrayList<Fragment> mFragmentList) {

        FragmentHelper.getInstance().showFragment(this, framLayoutId,position,mFragmentList);
    }

    /**
     * 创建Handler实例
     * Create a Handler instance
     */
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            decodeHandleMessage(msg);
        }
    };

    /**
     * 处理Handler接收到的消息
     * Processing Handler receives the message
     *
     * @param msg
     */
    protected void decodeHandleMessage(Message msg) {

    }

}

BaseActivity同理,这里就不做多解释,Dialog PopupWindow也需要在基类封装,这里不做累赘叙述,下面来看FragmentHelper(还可以扩展动画)类:


import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;

import java.util.ArrayList;

/**
 * Created by LanYan on 15/11/18.
 */
public class FragmentHelper {

    public static FragmentHelper instance;

    public FragmentHelper(){

    }
    public static FragmentHelper getInstance(){

        if(instance==null){
            synchronized (FragmentHelper.class){
                if(instance==null){
                    instance=new FragmentHelper();
                }
            }
        }
        return instance;
    }
    /**
     * 显示指定的Fragment
     * According to the specified fragments
     *
     * @param framLayoutId
     * @param cls
     * @param <T>
     */
    public <T extends Fragment> void replaceFragment(FragmentActivity mFragmentActivity,int framLayoutId, Class<T> cls) {
        replaceFragment(mFragmentActivity,framLayoutId, cls, null);
    }

    /**
     * 显示指定的Fragment
     * According to the specified fragments
     *
     * @param framLayoutId
     * @param cls
     * @param tag
     * @param <T>
     */
    public <T extends Fragment> void replaceFragment(FragmentActivity mFragmentActivity,int framLayoutId, Class<T> cls, String tag) {
        FragmentManager mFragmentManager = mFragmentActivity.getSupportFragmentManager();
        FragmentTransaction mTransaction = mFragmentManager.beginTransaction();

        T t = null;
        try {
            t = cls.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        if (tag == null) {
            mTransaction.replace(framLayoutId, t, cls.getName());
        } else {
            mTransaction.replace(framLayoutId, t, tag);
        }
        mTransaction.commit();
    }

    public <T extends Fragment> ArrayList<Fragment> addFragmentList(FragmentActivity mFragmentActivity,int framLayoutId, Class<T>[] clsList) {
        return addFragmentList(mFragmentActivity,framLayoutId, clsList, null);
    }

    public <T extends Fragment> ArrayList<Fragment> addFragmentList(FragmentActivity mFragmentActivity,int framLayoutId, Class<T>[] clsList, String tag) {

        ArrayList<Fragment> mFragmentList = new ArrayList<>();

        FragmentManager mFragmentManager = mFragmentActivity.getSupportFragmentManager();
        FragmentTransaction mTransaction = mFragmentManager.beginTransaction();

        for (int i = 0; i < clsList.length; i++) {
            T t = null;
            try {
                t = clsList[i].newInstance();
                mTransaction.add(framLayoutId, t, tag == null ? clsList[i].getName() : tag);
                mFragmentList.add(t);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        mTransaction.commit();

        return mFragmentList;
    }

    /**
     * 显示指定的Fragment
     * According to the specified fragments
     */
    public <T extends Fragment> void showFragment(FragmentActivity mFragmentActivity,int framLayoutId, int position, ArrayList<Fragment> mFragmentList) {

        FragmentManager mFragmentManager = mFragmentActivity.getSupportFragmentManager();
        FragmentTransaction mTransaction = mFragmentManager.beginTransaction();
        for (int i = 0; i < mFragmentList.size(); i++) {
            if (i == position) {
                mTransaction.show(mFragmentList.get(i));
            } else {
                mTransaction.hide(mFragmentList.get(i));
            }
        }
        mTransaction.commit();
    }


}

下面是GsonHelper泛型解析数据:


import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class GsonHelper {
    private static GsonHelper mInstance;
    private Gson mGson;
    public GsonHelper(){
        mGson=new Gson();
    }
    public static GsonHelper getInstance(){
        if(mInstance==null){
            synchronized (GsonHelper.class) {
                if(mInstance==null){
                    mInstance=new GsonHelper(); 
                }
            }
        }
        return mInstance;
    }

    public <T> ArrayList<T> fromJsonList(String json, Class<T> cls) {  
        ArrayList<T> mList = new ArrayList<T>();  
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();  
        for(final JsonElement elem : array){  
            mList.add(mGson.fromJson(elem, cls));  
        }  
        return mList;  
    }

    public <T> T fromJsonObject(String json, Class<T> cls){
        return mGson.fromJson(json, cls);
    }
    public <T> String toJson(Object mObject){
        return mGson.toJson(mObject);
    }
}

图片转String 工具类:


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.util.Base64;
/**
 * Created by LanYan on 2015/11/17.
 */
public class UploadImageHelper {

    private static UploadImageHelper instance;

    public UploadImageHelper() {

    }

    public static UploadImageHelper getInstance() {

        if (instance == null) {
            synchronized (UploadImageHelper.class) {
                if (instance == null) {
                    instance = new UploadImageHelper();
                }
            }
        }
        return instance;
    }

    /**
     * The picture file is transformed into a String
     * @param file
     * @return String
     */
    public String getStringWithFile(File file) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Base64.encodeToString(data, 0);
    }

    /**
     * The Bitmap is transformed into a String
     * @param bitmap
     * @return String
     */
    public String getStringWithBitmap(Bitmap bitmap)  
    {  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        bitmap.compress(CompressFormat.PNG, 100, baos);  
        byte[] appicon = baos.toByteArray(); 
        return Base64.encodeToString(appicon, Base64.DEFAULT);  

    }

    /**
     * According to the image path, the image is transformed into a String
     * @param url
     * @return String
     */
    public String getStringWithImageUrl(String url)  
    {  
        Bitmap mBitmap=BitmapFactory.decodeFile(url);
        mBitmap=zipImage(mBitmap, 200, 200);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        mBitmap.compress(CompressFormat.PNG, 100, baos);  
        byte[] appicon = baos.toByteArray();  
        return Base64.encodeToString(appicon, Base64.DEFAULT);  

    }


    /**
     * The compressed image
     * @param bgimage
     * @param newWidth
     * @param newHeight
     * @return Bitmap
     */
    public Bitmap zipImage(Bitmap bgimage, double newWidth,
            double newHeight) {
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }
}

Http请求响应类封装解析:


import java.io.Serializable;
import java.util.ArrayList;

import com.example.http.RespMessage;
/**
 * Request response bean
 * Created by LanYan on 2015/11/17.
 */
public class ResponseBean extends RespMessage implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -3190468559588437672L;

    private boolean hasNext;

    public boolean isHasNext() {
        return hasNext;
    }

    public void setHasNext(boolean hasNext) {
        this.hasNext = hasNext;
    }

    public <T> T getResultObject(Class<T> cls) {

        return GsonHelper.getInstance().fromJsonObject(getData(), cls);
    }

    public <T> ArrayList<T> getResultList(Class<T> cls) {

        ArrayList<T> mList = GsonHelper.getInstance().fromJsonList(getData(),
                cls);
        setHasNext(hasNextPage(mList));

        return mList;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

    public boolean getStatus() {
        return "00000000".equals(getRespCode()) ? true : false;
    }

    public <T> boolean hasNextPage(ArrayList<T> mList) {

        if (mList == null || mList.size() < 10) {
            return false;
        } else {
            return true;
        }
    }

}

封装可读性接口:


/**
 * Created by LanYan on 2015/11/17.
 */
public enum Iinterface {

    login(
    /** 登录*/
    "login",
    /** 登录账户、密码 */
    new String[]{
            /**登录手机号(需要MD5)*/
            "userName",
            /**登录密码*/
            "password"
    }),
    loading(
            /**启动界面Loading初始数据*/
            "",
            null
    );
    private Iinterface(String requestUrl,
            String[] postKey) {
        this.postKey = postKey;
        this.requestUrl = requestUrl;
    }

    private String requestUrl;
    private String[] postKey = null;
    public static final int ipIndex=23;
    public static final String host = "http://192.168.3."+ipIndex+":8080/xxxx/";

    public String[] getRequestpostKey() {

        return postKey;
    }

    public String getRequestUrl() {

        return host + requestUrl;
    }
}

SharedPeference简单封装:


import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.huianrong.app.http.GsonHelper;

@SuppressLint("CommitPrefEdits")
public class SharedPeferenceManager {

    private static SharedPeferenceManager instance;
    private static Context mContext;

    public SharedPeferenceManager() {

    }

    public static SharedPeferenceManager getInstance(Context context) {
        mContext = context;
        if (instance == null) {
            synchronized (SharedPeferenceManager.class) {
                if (instance == null) {
                    instance = new SharedPeferenceManager();
                }
            }
        }

        return instance;
    }

    public <T> T readObject(String tableName, String key, Class<T> cls) {

        String json = null;
        json = getSharedPreference(tableName).getString(key, null);

        return json==null?null:GsonHelper.getInstance().fromJsonObject(json, cls);
    }

    public <T> ArrayList<T> readList(String tableName,String key, Class<T> cls) {
        String json = null;
        json = getSharedPreference(tableName).getString(key, null);

        return GsonHelper.getInstance().fromJsonList(json, cls);
    }

    public <T> void saveOrUpdateObject(String tableName, String key, T t) {

        addObject(tableName, key, t, null);
    }

    public <T> void saveOrUpdateList(String tableName, String key,
            ArrayList<T> mList) {

        addList(tableName, key, mList, null);
    }

    public <T> void addObject(String tableName, String key, T t,
            Class<T> cls) {
        SharedPreferences mSharedPreferences =getSharedPreference(tableName);
        Editor mEditor=getEditor(mSharedPreferences);
        if(cls==null){
            mEditor.putString(key, GsonHelper.getInstance().toJson(t));
        }else {
            String requestJson=mSharedPreferences.getString(key, null);
            ArrayList<T> mList=new ArrayList<T>();
            if(requestJson!=null){
                mList=GsonHelper.getInstance().fromJsonList(requestJson, cls);
            }
            mList.add(t);
            mEditor.putString(key, GsonHelper.getInstance().toJson(mList));
        }
        mEditor.commit();
    }

    public <T> void addList(String tableName, String key,
            ArrayList<T> list, Class<T> cls) {

        SharedPreferences mSharedPreferences =getSharedPreference(tableName);
        Editor mEditor=getEditor(mSharedPreferences);
        if(cls==null){
            mEditor.putString(key, GsonHelper.getInstance().toJson(list));
        }else {
            String requestJson=mSharedPreferences.getString(key, null);
            ArrayList<T> mList=new ArrayList<T>();
            if(requestJson!=null){
                mList=GsonHelper.getInstance().fromJsonList(requestJson, cls);
            }
            mList.addAll(list);
            mEditor.putString(key, GsonHelper.getInstance().toJson(mList));
        }
        mEditor.commit();

    }

    public SharedPreferences getSharedPreference(String tableName) {

        return mContext.getSharedPreferences(tableName, Activity.MODE_PRIVATE);
    }

    public Editor getEditor(String tableName) {

        return getSharedPreference(tableName).edit();
    }

    public Editor getEditor(SharedPreferences mSharedPreferences) {

        return mSharedPreferences.edit();
    }
}

下面该是BaseFragment了:


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

import com.lidroid.xutils.ViewUtils;

/**
 * Created by LanYan on 2015/11/17.
 */
public abstract class BaseFragment extends Fragment {

    View contentView;
    protected FragmentActivity activity;

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

        if(contentView==null){
            contentView=inflater.inflate(setContentViewId(),null);
            ViewUtils.inject(this,contentView);
            initiazed();
        }
        return contentView;
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        return super.onCreateAnimation(transit, enter, nextAnim);
    }

    /**
     * onCreateView>inflater.inflate(setContentViewId(),null);
     * @return R.layout.xx
     */
    protected abstract int setContentViewId();

    /**
     * Initiazetion options
     */
    protected void initiazed(){
        activity=(BaseFragmentActivity)getActivity();
    }
}

有了一系列的基类可以帮助我们简化开发,下面是一个小的simple:


import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;

import com.huianrong.app.base.BaseFragmentActivity;
import com.huianrong.app.fragment.LoadingFragment;

public class SplashActivity extends BaseFragmentActivity {

    @Override
    public void applyTheme() {
        super.applyTheme();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * When the activity call the setContentView (int layout) method, this method is called to return to the layout
     * 当activity 调用setContentView(int layout) 方法时,调用此方法返回Layout
     *
     * @return R.layout.xx
     */
    @Override
    public int setContentViewId() {
        return R.layout.activity_splash;
    }

    @Override
    public void initiazed() {
        super.initiazed();
        replaceFragment(R.id.splash_frameLayout,LoadingFragment.class);
    }
}

下面是一个基于xutils http模块重新打包封装后的一个post请求实例:

        InterfaceManager manager=InterfaceManager.getInstance();
        manager.login(new String[]{"15828845121","12345"}, new HuiRequestCallBack() {
            @Override
            public void huiSuccess(ResponseBean response) {
                UserBean mUserBean=response.getResultObject(UserBean.class);
            }

            @Override
            public void huiFailure(Exception e, String message) {

            }
        });

零零乱乱的一地思绪,总结出:开发需要Fragment系列:BaseFragmentActivity、BaseFragment、FragmentHelper,Activity系列:BaseActivity、BaseView、BaseDialogFragment、BasePopupWindow、(弹出视图通过BaseView获取View视图传入弹出视图例如BaseDialogFragment等)、BaseBean等待;还需要辅助工具类:CheckInputHelper、CacheHelper等。同时Http网络请求模块需要封装请求,图片注意缓存,那么写好这些东西,考虑清楚项目需求就可以进入开发了,当开发的app程序多了,就会发现很多通用功能,而且每个app的更新会让用户体验不好,我们就应该考虑插件化开发,模块化。我不知道我的技术目前还在什么阶段,但是我知道我还是个菜逼,哎,大腿难求!!

1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:201291次
    • 积分:3018
    • 等级:
    • 排名:第12739名
    • 原创:93篇
    • 转载:0篇
    • 译文:1篇
    • 评论:136条
    博客专栏
    最新评论