Pro Android with Kotlin


Download 5.42 Mb.
Pdf ko'rish
bet125/223
Sana04.11.2023
Hajmi5.42 Mb.
#1746807
1   ...   121   122   123   124   125   126   127   128   ...   223
Bog'liq
@de android telegram Pro Android with Kotlin Developing Modern Mobile

141
CHAPTER 8: APIs

Reading the documentation, it seems necessary to use loaders only 
in conjunction with fragments. The truth is, the Loader framework has 
nothing to do with fragments per se; you can use fragments, if you like, 
but you don’t have to. So, you can use loaders with standard activities 
as well.
In the following paragraphs, we present a basic example for using the Loader framework. 
Experiment with it and extend it according to your needs.
As mentioned, inside an activity we have a LoaderManager already at hand; just use 
loaderManager, which by Kotlin gets internally transcribed to getLoaderManager().
Next we provide an implementation of LoaderManager.LoaderCallbacks. You can use your 
own class, but for simplicity you can implement it directly over your activity as follows:
class MainActivity : AppCompatActivity(),
LoaderManager.LoaderCallbacks {
val LOADER_ID = 42
var loaded:MyData? = null
// other fields and methods...
override fun onCreateLoader(id: Int, args: Bundle?):
Loader? {
Log.e("LOG", "onCreateLoader()")
return makeLoader()
}
override fun onLoadFinished(loader: Loader?,
data: MyData?) {
Log.e("LOG", "Load finished: " + data)
loaded = data
// show on UI or other actions...
}
override fun onLoaderReset(loader: Loader?) {
Log.e("LOG", "onLoaderReset()")
loaded = null
// remove from UI or other actions...
}
}
What we have here is the following:

The LOADER_ID is a unique ID for a loader. An app might have several 
loaders at work, so the Loader framework needs to be able to 
distinguish among different loaders.

var loaded:MyData? = null will later receive the result from the loading 
process. Note that it is not necessary to keep a reference to the Loader 
itself, and you actually shouldn’t do it, because the Loader framework 
will be taking care of the lifecycle of the loaders.



Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   121   122   123   124   125   126   127   128   ...   223




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling