Android learning notes
Creating Views Dynamically
var textViewAppContext = new TextView(getApplicationContext() /* also "this" if you want to do activity */)
// set some stuff on the textView
layout.addView(textViewAppContext)
Context
-
a handle to the android system
- Resources layouts, strings, images
- System services (LayouteInflator, SharedPreferences...)
- Launching Activities
- Access Databases
- Etc...
-
Typical Subclasses
- Activity
- Application
- Service
-
Activity Context only lasts as long as it's alive
- if you hold a reference to it you could cause a memory leak because it won't allow the Activity to garbage collect
-
Application lasts forever?
getApplicationContext()
-
Often you pass "this"?
ViewPager
-
ViewPager → Controlls the actually swiping between views
-
ViewPager gets it's content from a PagerAdapter
-
1 View per page → Pager Adapter
-
A Fragment for each page → FragmentPagerAdapter (for fragments)
- this keeps each page in memory, which can be expensive if you have a lot
-
FragmentStatePagerAdapter
- Destory & Recreate fragments
ViewPager2 is the one I should use
ViewModel
learned from: https://www.youtube.com/watch?v=5qlIPTDE274
View Models survive "Configuration Changes"
Rotating a phone basically tears down your activity and re-creates it
this clears out all local state
ViewModels survive therefore don't have this problem
Also they have a better separation of concerns
- ViewModel: holds UI data (Login form state, etc...)
- Activity: Displays the ViewModel's UI centric data
- Repository: API for saving/loading app data
WARNING: these do not save their state if the process closes down, onSaveInstanceState
does
LiveData
A class that will broadcast changes to data (create reactive data)