Android Architecture Components samples analyse

1.BasicSample - Shows how to persist data using a SQLite database and Room. Also uses ViewModels and LiveData.

此 sample 需求非常簡(jiǎn)單, 使用 list 展示(持久化)數(shù)據(jù)庫(kù)中的數(shù)據(jù), 點(diǎn)擊每個(gè) item 可以進(jìn)入到詳情頁(yè)(展示詳情信息)

1.1MainActivity.java -- main_activity.xml

作為一個(gè) fragment 的載體, 僅僅包括一個(gè) fragment: 1.2ProductListFragment.java
還有個(gè) public method 展示ProductFragment.java(一會(huì)再來(lái)看)

1.2ProductListFragment.java -- list_fragment.xml

此界面中有2個(gè) view, 一個(gè)是加載完成前的 loading 提示view, 一個(gè)是加載完成后的 recyclerView

1.2ProductListFragment 中使用了android.databinding 進(jìn)行 fragment, xml 和數(shù)據(jù)的綁定
onCreateView() 中 init:

private ListFragmentBinding mBinding;
mBinding = DataBindingUtil.inflate(inflater, R.layout.list_fragment, container, false);

在 list_fragment.xml 中,
--1.使用<data> 標(biāo)簽,聲明 var
--2.使用 app:visibleGone="@{isLoading}" 對(duì) view 進(jìn)行動(dòng)態(tài)控制

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="isLoading"
            type="boolean" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/cardview_light_background"
        android:orientation="vertical">

        <TextView
            android:id="@+id/loading_tv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_vertical|center_horizontal"
            android:text="@string/loading_products"
            android:textAlignment="center"
            app:visibleGone="@{isLoading}"
            />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/products_list"
            android:contentDescription="@string/cd_products_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layoutManager="LinearLayoutManager"
            app:visibleGone="@{!isLoading}"/>

    </LinearLayout>
</layout>

--3.${visibleGone} 關(guān)鍵字在 BindingAdapters.java 中被自定義, 然后 showHide() 方法對(duì) view 進(jìn)行動(dòng)態(tài)控制

public class BindingAdapters {
    @BindingAdapter("visibleGone")
    public static void showHide(View view, boolean show) {
        view.setVisibility(show ? View.VISIBLE : View.GONE);
    }
}

--4. 而 showHide() 是在ListFragmentBinding.java 中被調(diào)用, 是自動(dòng)生成的


public class ListFragmentBinding extends android.databinding.ViewDataBinding  {
...
 com.example.android.persistence.ui.BindingAdapters.showHide(this.loadingTv, isLoading);
 com.example.android.persistence.ui.BindingAdapters.showHide(this.productsList, IsLoading1);
...
}

--5.適配器 ProductAdapter.java 對(duì)數(shù)據(jù)和 fragment 進(jìn)行關(guān)聯(lián)

 mProductAdapter = new ProductAdapter(mProductClickCallback);

--6.獲取數(shù)據(jù)
在onActivityCreated() 中, 獲取數(shù)據(jù):

 final ProductListViewModel viewModel = ViewModelProviders.of(this).get(ProductListViewModel.class);
    
 // Update the list when the data changes        
 viewModel.getProducts().observe(this, new Observer<List<ProductEntity>>() {
            @Override
            public void onChanged(@Nullable List<ProductEntity> myProducts) {
                if (myProducts != null) {
                    mBinding.setIsLoading(false);
                    mProductAdapter.setProductList(myProducts);
                } else {
                    mBinding.setIsLoading(true);
                }
            }
        });

這段代碼使用了新的方式獲取數(shù)據(jù)庫(kù)中的數(shù)據(jù):ViewModelProviders.of(this).get(ProductListViewModel.class);
--7.ProductListViewModel.java
ViewModelProviders為arch 中的方法;
此處我們需要實(shí)現(xiàn)如下: 在 apply() 中有 loadAllProducts()的方法, 此方法實(shí)現(xiàn)在 Dao 中

public class ProductListViewModel extends AndroidViewModel {

    private static final MutableLiveData ABSENT = new MutableLiveData();
    {
        //noinspection unchecked
        ABSENT.setValue(null);
    }

    private final LiveData<List<ProductEntity>> mObservableProducts;

    public ProductListViewModel(Application application) {
        super(application);

        final DatabaseCreator databaseCreator = DatabaseCreator.getInstance(this.getApplication());

        LiveData<Boolean> databaseCreated = databaseCreator.isDatabaseCreated();
        mObservableProducts = Transformations.switchMap(databaseCreated,
                new Function<Boolean, LiveData<List<ProductEntity>>>() {
            @Override
            public LiveData<List<ProductEntity>> apply(Boolean isDbCreated) {
                if (!Boolean.TRUE.equals(isDbCreated)) { // Not needed here, but watch out for null
                    //noinspection unchecked
                    return ABSENT;
                } else {
                    //noinspection ConstantConditions
                    return databaseCreator.getDatabase().productDao().loadAllProducts();
                }
            }
        });

        databaseCreator.createDb(this.getApplication());
    }

    /**
     * Expose the LiveData Products query so the UI can observe it.
     */
    public LiveData<List<ProductEntity>> getProducts() {
        return mObservableProducts;
    }
}

--8.ProductEntity.java
@Entity 是 新的包 arch.room 中的
此類是Product 的實(shí)體類:
@Entity(tableName = "products"): 表名為"products"
@PrimaryKey private int id; : primary key 為 id

@Entity(tableName = "products")
public class ProductEntity implements Product {
    @PrimaryKey
    private int id;
    private String name;
    private String description;
    private int price;

    @Override
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public ProductEntity() {
    }

    public ProductEntity(Product product) {
        this.id = product.getId();
        this.name = product.getName();
        this.description = product.getDescription();
        this.price = product.getPrice();
    }
}

--9.ProductDao.java
@Dao 是新的包 arch.room 中的
形如 retrofit2的接口請(qǐng)求, 實(shí)現(xiàn)起來(lái)的方式和retrofit 很像

@Dao
public interface ProductDao {
    @Query("SELECT * FROM products") 
    LiveData<List<ProductEntity>> loadAllProducts();

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertAll(List<ProductEntity> products);

    @Query("select * from products where id = :productId")
    LiveData<ProductEntity> loadProduct(int productId);

    @Query("select * from products where id = :productId")
    ProductEntity loadProductSync(int productId);
}

--10.上一張圖簡(jiǎn)單理解下 View ViewModel model 的關(guān)系

final-architecture.png

2.GithubBrowserSample - An advanced sample that uses the Architecture components, Dagger and the Github API. Requires Android Studio 3.0 canary 1

--1.MainActivity.java
implements LifecycleRegistryOwner

    @Override
    public LifecycleRegistry getLifecycle() {
        return lifecycleRegistry;
    }

implements HasSupportFragmentInjector

 @Override
    public DispatchingAndroidInjector<Fragment> supportFragmentInjector() {
        return dispatchingAndroidInjector;
    }

通過注入NavigationController 控制 fragment

@Inject
    NavigationController navigationController;
    @Inject
    public NavigationController(MainActivity mainActivity) {
        this.containerId = R.id.container;
        this.fragmentManager = mainActivity.getSupportFragmentManager();
    }

    public void navigateToSearch() {
        SearchFragment searchFragment = new SearchFragment();
        fragmentManager.beginTransaction()
                .replace(containerId, searchFragment)
                .commitAllowingStateLoss();
    }

--2.SearchFragment.java
dataBinding

 <data>
        <import type="com.android.example.github.vo.Repo"/>
        <import type="java.util.List"/>
        <import type="com.android.example.github.vo.Status"/>
        <import type="com.android.example.github.vo.Resource"/>
        <variable name="resultCount" type="int"/>
        <variable name="query" type="String"/>
        <variable name="loadingMore" type="boolean"/>
        <variable name="searchResource" type="Resource"/>
        <variable name="callback" type="com.android.example.github.ui.common.RetryCallback"/>
    </data>

SearchFragmentBinding dataBinding = DataBindingUtil
                .inflate(inflater, R.layout.search_fragment, container, false,
                        dataBindingComponent);

extends LifecycleFragment

功能1:searching function:

    private void doSearch(View v) {
        //get query key word
        String query = binding.get().input.getText().toString();
        // Dismiss keyboard
        dismissKeyboard(v.getWindowToken());
        binding.get().setQuery(query);
        searchViewModel.setQuery(query);
    }

--3.SearchViewModel.java
extends ViewModel
功能1:refresh()

    void refresh() {
        if (query.getValue() != null) {
            query.setValue(query.getValue());
        }
    }

功能2:loadNextPage()

    void loadNextPage() {
        String value = query.getValue();
        if (value == null || value.trim().length() == 0) {
            return;
        }
        nextPageHandler.queryNextPage(value);
    }

--4.DAO @Dao
RepoDao.java
UserDao.java
--5.Entity @Entity
RepoEntity.java
UserEntity.java
RepoSearchResultEntity.java
ContributorEntity.java
--6.GithubService.java

    @GET("users/{login}")
    LiveData<ApiResponse<User>> getUser(@Path("login") String login);

    @GET("users/{login}/repos")
    LiveData<ApiResponse<List<Repo>>> getRepos(@Path("login") String login);

    @GET("repos/{owner}/{name}")
    LiveData<ApiResponse<Repo>> getRepo(@Path("owner") String owner, @Path("name") String name);

    @GET("repos/{owner}/{name}/contributors")
    LiveData<ApiResponse<List<Contributor>>> getContributors(@Path("owner") String owner, @Path("name") String name);

    @GET("search/repositories")
    LiveData<ApiResponse<RepoSearchResponse>> searchRepos(@Query("q") String query);

    @GET("search/repositories")
    Call<RepoSearchResponse> searchRepos(@Query("q") String query, @Query("page") int page);

--7.repository
RepoRepository.java

GithubDb db;
//操作數(shù)據(jù)庫(kù)
RepoDao repoDao;
//網(wǎng)絡(luò)操作
GithubService githubService;
AppExecutors appExecutors;

UserRepository.java

//操作數(shù)據(jù)庫(kù)
UserDao userDao;
//網(wǎng)絡(luò)操作
GithubService githubService;
AppExecutors appExecutors;

--8.AppComponent.java

@Singleton
@Component(modules = {
        AndroidInjectionModule.class,
        AppModule.class,
        MainActivityModule.class
})
public interface AppComponent {
    @Component.Builder
    interface Builder {
        @BindsInstance Builder application(Application application);
        AppComponent build();
    }
    void inject(GithubApp githubApp);
}

--9.AppModule.java

@Module(includes = ViewModelModule.class)

 @Singleton @Provides
    GithubService provideGithubService() {
        return new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(new LiveDataCallAdapterFactory())
                .build()
                .create(GithubService.class);
    }

    @Singleton @Provides
    GithubDb provideDb(Application app) {
        return Room.databaseBuilder(app, GithubDb.class,"github.db").build();
    }

    @Singleton @Provides
    UserDao provideUserDao(GithubDb db) {
        return db.userDao();
    }

    @Singleton @Provides
    RepoDao provideRepoDao(GithubDb db) {
        return db.repoDao();
    }

--10.MainActivityModule.java

@ContributesAndroidInjector(modules = FragmentBuildersModule.class)
    abstract MainActivity contributeMainActivity();


--11.FragmentBuildersModule.java

    @ContributesAndroidInjector
    abstract RepoFragment contributeRepoFragment();

    @ContributesAndroidInjector
    abstract UserFragment contributeUserFragment();

    @ContributesAndroidInjector
    abstract SearchFragment contributeSearchFragment();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末钢坦,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子校翔,更是在濱河造成了極大的恐慌配乱,老刑警劉巖阳啥,帶你破解...
    沈念sama閱讀 217,734評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件铐姚,死亡現(xiàn)場(chǎng)離奇詭異证九,居然都是意外死亡彭谁,警方通過查閱死者的電腦和手機(jī)吸奴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)缠局,“玉大人则奥,你說我怎么就攤上這事∠猎埃” “怎么了读处?”我有些...
    開封第一講書人閱讀 164,133評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)妙啃。 經(jīng)常有香客問我档泽,道長(zhǎng),這世上最難降的妖魔是什么揖赴? 我笑而不...
    開封第一講書人閱讀 58,532評(píng)論 1 293
  • 正文 為了忘掉前任馆匿,我火速辦了婚禮,結(jié)果婚禮上燥滑,老公的妹妹穿的比我還像新娘渐北。我一直安慰自己,他們只是感情好铭拧,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評(píng)論 6 392
  • 文/花漫 我一把揭開白布赃蛛。 她就那樣靜靜地躺著,像睡著了一般搀菩。 火紅的嫁衣襯著肌膚如雪呕臂。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,462評(píng)論 1 302
  • 那天肪跋,我揣著相機(jī)與錄音歧蒋,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛谜洽,可吹牛的內(nèi)容都是我干的萝映。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼阐虚,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼序臂!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起实束,我...
    開封第一講書人閱讀 39,153評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤奥秆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后磕洪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體吭练,經(jīng)...
    沈念sama閱讀 45,587評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡诫龙,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評(píng)論 3 336
  • 正文 我和宋清朗相戀三年析显,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片签赃。...
    茶點(diǎn)故事閱讀 39,919評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡谷异,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出锦聊,到底是詐尸還是另有隱情歹嘹,我是刑警寧澤,帶...
    沈念sama閱讀 35,635評(píng)論 5 345
  • 正文 年R本政府宣布孔庭,位于F島的核電站尺上,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏圆到。R本人自食惡果不足惜怎抛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望芽淡。 院中可真熱鬧马绝,春花似錦、人聲如沸挣菲。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)白胀。三九已至椭赋,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間或杠,已是汗流浹背哪怔。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蔓涧。 一個(gè)月前我還...
    沈念sama閱讀 48,048評(píng)論 3 370
  • 正文 我出身青樓件已,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親元暴。 傳聞我的和親對(duì)象是個(gè)殘疾皇子篷扩,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容