Kotlin Android Extensions+Android MVP項目 [復制鏈接]

2018-12-24 10:28
liujh 閱讀:534 評論:0 贊:0
Tag:  
Kotlin編寫MVP案例
使用Kotlin編程實現一個MVP案例,實現電影列表功能:



前期準備:
項目中,在Gradle中引入框架的配置如下和使用Kotlin Android擴展:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'//擴展插件

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    //Glide v4
    compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC0'
    //Retrofit 2.x
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    //OkHttp 3.x
    compile 'com.squareup.okhttp3:okhttp:3.8.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
    //RxJava 1.x
    compile 'io.reactivex:rxjava:1.3.0'
    compile 'io.reactivex:rxandroid:1.2.1'
}

須注意點:本篇中無findViewById獲取控件對象,采用Kotlin Android Extensions方式獲取控件對象。
AndroidManifest.xml中添加權限:

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

除之外,還有各種框架的混淆規則,這里省略不貼。

開始編寫代碼:

1. 項目通用的BasePrester和BaseView接口:
項目中通用的BasePresenter接口,具備訂閱和取消訂閱的行為:

interface  BasePresenter{
    /**
     * 訂閱
     */
    fun subscribe()
    /**
     * 取消訂閱
     */
     fun unsubscribe()
}

項目中通用的BaseView接口,具備綁定Presenter的行為:

interface BaseView<T>{
    /**
     * 設置Presenter的方法
     */
    fun  setPresenter(presenter: T)
}

2. 開始編寫Model中遠程數據源
采用Retrofit作為網絡異步框架,OkHttp作為傳輸層。

這里,采用搜索張藝謀的電影,在douban的API中:https://api.douban.com/v2/movie/search?q=張藝謀

Retrofit的請求和響應結果的配置:請求中發送的Body和Header,Respose的接口 :需要添加retrofit:adapter-rxjava庫,實現適配器功能

interface DouBanService {
    /**
     *     這里返回一個Observable,用于RxJava結合使用
     */
    @GET("{path}")
    fun movieList(@Path("path") path:String, @QueryMap options: Map<String,String> ):Observable<MovieList>
}

Retrofit的操作類:添加OkHttp作為傳輸層,RxJava適配器,Gson解析的轉換器。

object RemoteDataSource{
    val baseURL="https://api.douban.com/v2/movie/"
    val retrofit:Retrofit by lazy {
        Retrofit.Builder().baseUrl(baseURL)
                .client(OkHttpProvider.createOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
    }
    var douBanService= retrofit.create(DouBanService::class.java)

    fun movieList(subscriber:Subscriber<List<MovieList.Movie>>):Subscription{
        val url="search"
        var map= hashMapOf("q" to "張藝謀" )
         var result= douBanService.movieList(url,map).flatMap {
            item: MovieList ->Observable.just(item.subjects)
        }.subscribeOn(Schedulers.io())
        .unsubscribeOn(Schedulers.io()) 
        .observeOn(AndroidSchedulers.mainThread()) 
        .subscribe(subscriber)

        return result
    }
}

OkHttp的配置:需 引入OkHttp庫和OkHttp:logging-interceptor庫

internal class OkHttpProvider{
    companion object{
        /**
         * 自定義配置OkHttpClient
         */
        fun createOkHttpClient():OkHttpClient{
           var  builder=OkHttpClient.Builder()
            var  loggingInterceptor=HttpLoggingInterceptor()
            loggingInterceptor.level=HttpLoggingInterceptor.Level.BODY
            builder.addInterceptor(loggingInterceptor)
            return builder.build()
        }
    }
}

編寫返回的實體類:

data  class MovieList(var subjects:List<Movie>){
    data class Movie(var year:String,var title:String,var  images: Images){
        data class Images(var small:String,var large:String)
    }
}
上篇已經詳細介紹了,請閱讀Kotlin編程之Glide v4 Generated API(Unresolved reference GlideApp)。

3. 根據模塊業務編寫View和Presenter及它的實現類
業務上比較簡單,搜索張藝謀的電影,顯示在列表上。根據這個分析,寫出這個模塊的View和Presenter.

interface MovieListConstract{
    interface Presenter:BasePresenter
    /***
     * 抽出Presenter對View的響應行為,在View接口中定義
     */
    interface View :BaseView<Presenter>{
        fun showToast(msg:String)//Toast提示
        fun loadMovie(list: List<MovieList.Movie>)//加載電影數據
        fun showDialog()//顯示dialog
        fun cancleDialog()//取消dialog
    }
}

View的實現類: 在Fragment、Activity、Adapter中怎么使用Kotlin Android Extensions.

class MovieListFragment : Fragment(), MovieListConstract.View {

    lateinit var presenters: MovieListConstract.Presenter
    lateinit var dialog: ProgressDialog
    lateinit var rootView: View 

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        rootView = inflater.inflate(R.layout.fragment_movielist, container, false)
        return rootView
    }
    override fun onResume() {
        super.onResume()
        presenters.subscribe()
    }
    override fun onPause() {
        super.onPause()
        presenters.unsubscribe()
    }
    override fun setPresenter(presenter: MovieListConstract.Presenter) {
        this.presenters = presenter
    }
    override fun showToast(msg: String) {
        Toast.makeText(activity.applicationContext, msg, Toast.LENGTH_SHORT).show()
    }
    /**
     * 加載數據
     */
    override fun loadMovie(list: List<MovieList.Movie>) {
        //無findViewById(),直接引用控件
        var recyclerView = rootView.movieList_recyclverView
        recyclerView.layoutManager = LinearLayoutManager(activity)
        recyclerView.adapter = MovieListAdapter(activity, list)
    }
    override fun showDialog() {
        dialog = ProgressDialog(activity)
        dialog.show()
    }
    override fun cancleDialog() {
        if (dialog != null && dialog.isShowing) {
            dialog.cancel()
        }
    }
    companion object {
        //靜態對象
        val instance = MovieListFragment()
        //靜態常量
        val Tag = MovieListFragment::class.java.javaClass.simpleName
    }
}

RecyclerView中Adapter:

import kotlinx.android.synthetic.main.movielist_item.view.*

/**
 * Created by ${新根} on 2017/6/8.
 * blog :http://blog.csdn.net/hexingen
 */
internal class MovieListAdapter(var context: Context, var list: List<MovieList.Movie>) : RecyclerView.Adapter<MovieListAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = 
              ViewHolder(View.inflate(parent.context, R.layout.movielist_item, null)) 

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        GlideUtils.loadUrlImage(context,list[position].images.large,holder.imageView)
        holder.title_Tv.text=list[position].title
    } 

    override fun getItemCount() = list.size 

    internal class ViewHolder(rootView: View) : RecyclerView.ViewHolder(rootView) {
        /**
         * 這里使用Kotlin Android 擴展,省略了findViewById().
         * 在最上面導入了import kotlinx.android.synthetic.main.movielist_item.view.*
         */
        var imageView = rootView.movielist_item_iv
        var title_Tv= rootView.movielist_item_tv
    }
}

Presenter的實現類:

class MovieListPresenter(var view: MovieListConstract.View, var compositeSubscription: CompositeSubscription = defaultCompositeSubscription) : MovieListConstract.Presenter {
    init {//init初始化模塊
        view.setPresenter(this)
    }
    //開始訂閱
    override fun subscribe() {
        view.showDialog()
        excuteTask()
    }
    //執行任務
    fun excuteTask() {
      var  disposable=RemoteDataSource.movieList(object :Subscriber<List<MovieList.Movie>>() {
            override fun onNext(t: List<MovieList.Movie>) = view.loadMovie(t)
            override fun onError(e: Throwable) {
                view.showToast(e.toString())
                view.cancleDialog()
            }
          override fun onCompleted() {
              view.showToast("加載完成")
              view.cancleDialog()
          }
      })
      this.compositeSubscription.add(disposable)
    }
    //取消訂閱,釋放資源
    override fun unsubscribe() {
        view.cancleDialog()
        compositeSubscription.clear()
    }
    companion object {//采用伴隨對象
        //默認的值
        val defaultCompositeSubscription get() = CompositeSubscription()
    }
}

Activity中創建View和Presenter:

class MovieListActvitiy : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_movielist) 

        //創建View實例
        var view=MovieListFragment.instance
        //創建Presenter實例
        MovieListPresenter(view)
        //添加fragment
        supportFragmentManager.beginTransaction() 
               .add(R.id.movielist_content_layout,view,MovieListFragment.Tag).commit()
    }
}

最終項目結構目錄如下:



4. 效果圖如下:

代碼:http://www.iddrgr.tw/thread-604724-1-1.html



我來說兩句
您需要登錄后才可以評論 登錄 | 立即注冊
facelist
所有評論(0)
領先的中文移動開發者社區
18620764416
7*24全天服務
意見反饋:[email protected]

掃一掃關注我們

Powered by Discuz! X3.2© 2001-2019 Comsenz Inc.( 粵ICP備15117877號 )

两码中特期期