讓你Android開發更簡單

來源:互聯網
上載者:User

標籤:成功   代碼   activity   sam   aries   wip   addtab   cli   adc   

轉載:http://www.jianshu.com/p/22ff8b5fdadc搭建一個新的Android項目,你會怎麼做?
每個人對應用程式框架的理解不相同,但是最終達到的效果應該是一樣:①降低項目的複雜性②易擴充、易修改、可重用性強、可維護性強③職責單一,功能清晰

在android開發項目中,我們首先要考慮每個項目的共同點,比如說:Mvp、網路請求層、Base存放View的基類、Log日誌、App crash、重新整理載入更多、Loading、廣告圖、支援ListView,RecyclerView的BaseAdater、通知欄沈浸式、圖片載入緩衝、底部導航功能...
那麼這些功能是每個項目都必須需要的功能,那麼可不可以以把這些通用的東西抽取呢?

項目工程搭建

App工程結構搭建:幾種常見Android代碼架構分析


App工程包結構.png

包名的作用一目瞭然,在別人接手這個項目的時候就會相對簡單

  • adapter 適配器,如果業務複雜,根據不同的業務可以添加子包來進行分類
  • api 網路請求層的封裝 retrofit &okhttp3 &rxjava
  • base 用來存放View的基類,例如BaseAcitivity、BaseFragment、BaseSwipeBackActivity、BasePresent
  • manage 用來存放一些通用的管理類: Crash、ImageLoader、Logger
  • model 封裝Mvp Logic池,通過註解的方式contact和presenter進行執行個體化和bindView,使用時直接使用mPresenter
  • ui 自訂View 滑動刪除,底部導航
common libraries 開源庫的選型
  • android-architecture: GoogleMvp樣本code-Android Architecture MVP + Dagger2
  • retrofit: retrofit Square出品的網路請求庫,極大的減少了http請求的代碼和步驟.
  • okhttp: 據說Android4.4的源碼中可以看到HttpURLConnection已經替換成OkHttp實現了
  • rxjava: rxjava提供優雅的響應式Api解決非同步請求.
  • ButterKnife: ButterKnife解放控制項對象執行個體化,從此告別findviewbyId
  • gilde: Google推薦:Glide功能強大圖片載入緩衝庫
  • LeakCanary: LeakCanarySquare出品的專門用來檢測Android和Java的記憶體流失
    //squareupcompile ‘com.squareup.retrofit2:retrofit:2.1.0‘compile ‘com.squareup.retrofit2:converter-gson:2.1.0‘compile ‘com.squareup.retrofit2:adapter-rxjava:2.1.0‘compile ‘com.squareup.okhttp3:logging-interceptor:3.4.1‘compile ‘com.jakewharton:butterknife:7.0.1‘compile ‘com.github.bumptech.glide:glide:3.7.0‘compile ‘io.reactivex:rxjava:1.1.5‘compile ‘io.reactivex:rxandroid:1.2.0‘compile ‘com.jcodecraeer:xrecyclerview:1.2.7‘
項目建立重構

對Android一些常用功能做一些整理封裝成basic架構,方便Android初始項目快速開發
https://github.com/meikoz/Basic

仿開眼Demo樣本:Basic+Retrofit+Okhttp+Rxjava+Glide
請大家多多關注star和提意見給予支援,從自己的一些實踐經驗來總結這部分通用的東西作為一份善意的分享。

How UsageStep 1:

Setup ‘Basic‘ dependencies in build.gradle file:

dependencies {    compile ‘com.meikoz.basic:core:1.0.5‘}
Step 2:

Create subclass of Application extends MainApplication,initialize basic BuildConfig.debug is true in super.onCreate() method before for debug print log.

public class BaseApp extends MainApplication {    @Override    public void onCreate() {        RestApi.getInstance().deBug(true);        super.onCreate();    }}
  • RestApi.getInstance().deBug(true); 是為了Debug列印日誌,請上線前刪掉此方法#重要#
Step 3:

app usage mvp pattern, View and Presenter need things.
View extends BaseView. Presenter extends BasePresenter<View>.

@Implement(MainLogicImpl.class)public interface MainLogicI {    void onLoadData2Remote();    interface MainView extends BaseView {        void onLoadSuccessHandler(String responce);    }}public class MainLogicImpl extends BasePresenter<MainLogicI.MainView>    implements MainLogicI {    @Override    public void onLoadData2Remote() {        getView().onLoadSuccessHandler("請求成功,返回的資料");    }}

How to initialize use the Activity.

class MainActivity extends Activity implements MainLogicI.MainView {   @Override    protected Class getLogicClazz() {        return your interface MainLogicI class;// MainLogic是Presenter要實現的介面    }    @Override    protected void onInitData2Remote() {        super.onInitData2Remote();       ((MainLogicImpl) mPresenter).onLoadData2Remote();    }    @Override    public void onLoadSuccessHandler(String response) {    //response是Presenter中返回的資料   }}
  • super.onInitData2Remote(); 會初始化Presnter並bindView
Step 4:

Network: Retrofit + okhttp
根據不同業務產生不同Service

public class ApiManager {    public static APIService createApi() {        return RestApi.getInstance().create(APIService.class);    }    public static UserService createUserApi() {        return RestApi.getInstance().create(UserService.class);    }}public interface APIService {    String BASE_URL ="https://github.com/";    @GET("api/v1/user")    Call<Response> getUserInfo(@Query("uid") int uid);}
cool featurefeature 1:實現 Tab +fragment 功能
QQ圖片20161121164914.png
public class MainAty extends AppCompatActivity {    private TabStripView navigateTabBar;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        navigateTabBar = (TabStripView) findViewById(R.id.navigateTabBar);        navigateTabBar.onRestoreInstanceState(savedInstanceState);        navigateTabBar.addTab(HomeFragment.class,            new TabStripView.TabParam(R.drawable.ic_tab_strip_icon_feed,                R.drawable.ic_tab_strip_icon_feed_selected,                R.string.tab_bar_text_feed));        navigateTabBar.addTab(DiscoveryFragment.class,            new TabStripView.TabParam(R.drawable.ic_tab_strip_icon_category,                R.drawable.ic_tab_strip_icon_category_selected,                R.string.tab_bar_text_category));        navigateTabBar.addTab(AutoFragment.class,            new TabStripView.TabParam(R.drawable.ic_tab_strip_icon_pgc,                R.drawable.ic_tab_strip_icon_pgc_selected,                R.string.tab_bar_text_pgc));        navigateTabBar.addTab(ProfileFragment.class,            new TabStripView.TabParam(R.drawable.ic_tab_strip_icon_profile,                R.drawable.ic_tab_strip_icon_profile_selected,                R.string.tab_bar_text_profile));    }    @Override    protected void onSaveInstanceState(Bundle outState) {        super.onSaveInstanceState(outState);        navigateTabBar.onSaveInstanceState(outState);    }}
feature 2:實現仿ios彈窗效果
預設取消確定按鈕.png
  • setCancelable(true) 預設顯示取消按鈕,用法和原生AlertDialog寫法一樣

    new SweetAlertDialog.Builder(MainActivity.this)           .setTitle("標題")           .setMessage("描述詳細內容?")           .setCancelable(true)           .setPositiveButton("確認", new SweetAlertDialog.OnDialogClickListener() {                @Override                 public void onClick(Dialog dialog, int which) {                    Toast.makeText(MainActivity.this, "確定按鈕", Toast.LENGTH_SHORT).show();                 }            })           .show();

    只有一個確定按鈕.png


    ![Uploading QQ圖片20161121171109_005140.png . . .]

  • setCancelable(false) 這樣就只顯示一個按鈕

    new SweetAlertDialog.Builder(MainActivity.this)           .setTitle("標題")           .setMessage("描述詳細內容?")           .setCancelable(false)           .setPositiveButton("確認", new SweetAlertDialog.OnDialogClickListener() {                @Override                 public void onClick(Dialog dialog, int which) {                    Toast.makeText(MainActivity.this, "確定按鈕", Toast.LENGTH_SHORT).show();                 }            })           .show();

    左右邊都設定按鈕.png
  • 左右按鈕自訂
    new SweetAlertDialog.Builder(MainActivity.this)           .setTitle("標題")           .setMessage("描述詳細內容?")           .setCancelable(false)           .setNegativeButton("左邊", new SweetAlertDialog.OnDialogClickListener() {                @Override                public void onClick(Dialog dialog, int which) {                            Toast.makeText(MainActivity.this, "左邊" + which, Toast.LENGTH_SHORT).show();                }})           .setPositiveButton("確認", new SweetAlertDialog.OnDialogClickListener() {                @Override                 public void onClick(Dialog dialog, int which) {                    Toast.makeText(MainActivity.this, "確定按鈕", Toast.LENGTH_SHORT).show();                 }            })           .show();
    feature 3:CommonAdapter for ListView, RecyclerAdapter for RecyclerViewCommonAdapter for ListView, RecyclerAdapter for RecyclerView
    實現 void convert(ViewHolder helper, T item); Replace getView();
feature 4:Logger 漂亮的日誌系統

Logger.d(message);
Logger.i(message);
Logger.e(message);
Logger.v(message);
Logger.json(message);


漂亮的日誌.pngTo do something v2.0.0
  • 網路請求前增加LoadingView,加完完成消失
  • 載入失敗統一失敗頁面,支援重新請求
  • Activity銷毀掉,關閉網路請求功能 避免報錯
  • EyepetizerApp: 使用Basic架構完成開眼App

 

讓你Android開發更簡單

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.