Kotlin - Android

16 Notes
+ Components of a RecyclerView (June 22, 2019, 1:26 p.m.)

1- LayoutManagers: A RecyclerView needs to have a layout manager and an adapter to be instantiated. A layout manager positions item views inside a RecyclerView and determines when to reuse item views that are no longer visible to the user. RecyclerView provides these built-in layout managers: - LinearLayoutManager shows items in a vertical or horizontal scrolling list. - GridLayoutManager shows items in a grid. - StaggeredGridLayoutManager shows items in a staggered grid. To create a custom layout manager, extend the RecyclerView.LayoutManager class. ------------------------------------------------------------------ 2- RecyclerView.Adapter RecyclerView includes a new kind of adapter. It’s a similar approach to the ones you already used, but with some peculiarities, such as a required ViewHolder. You will have to override two main methods: one to inflate the view and its view holder, and another one to bind data to the view. The good thing about this is that the first method is called only when we really need to create a new view. No need to check if it’s being recycled. ------------------------------------------------------------------ 3- ItemAnimator RecyclerView.ItemAnimator will animate ViewGroup modifications such as add/delete/select that are notified to the adapter. DefaultItemAnimator can be used for basic default animations and works quite well. See the section of this guide for more information. ------------------------------------------------------------------

+ RecyclerView Compared to ListView (June 22, 2019, 1:18 p.m.)

RecyclerView differs from its predecessor ListView primarily: - Required ViewHolder in Adapters - ListView adapters do not require the use of the ViewHolder pattern to improve performance. In contrast, implementing an adapter for RecyclerView requires the use of the ViewHolder pattern for which it uses RecyclerView.Viewholder. - Customizable Item Layouts - ListView can only layout items in a vertical linear arrangement and this cannot be customized. In contrast, the RecyclerView has a RecyclerView.LayoutManager that allows any item layouts including horizontal lists or staggered grids. - Easy Item Animations - ListView contains no special provisions through which one can animate the addition or deletion of items. In contrast, the RecyclerView has the RecyclerView.ItemAnimator class for handling item animations. - Manual Data Source - ListView had adapters for different sources such as ArrayAdapter and CursorAdapter for arrays and database results respectively. In contrast, the RecyclerView.Adapter requires a custom implementation to supply the data to the adapter. - Manual Item Decoration - ListView has the android:divider property for easy dividers between items in the list. In contrast, RecyclerView requires the use of a RecyclerView.ItemDecoration object to setup much more manual divider decorations. - Manual Click Detection - ListView has a AdapterView.OnItemClickListener interface for binding to the click events for individual items in the list. In contrast, RecyclerView only has support for RecyclerView.OnItemTouchListener which manages individual touch events but has no built-in click handling.

+ Difference between gravity and layout_gravity (June 12, 2019, 2:17 a.m.)

gravity: - sets the gravity of the contents (i.e. its subviews) of the View it's used on. - arranges the content inside the view. -------------------------------------------------------------- layout_gravity: - sets the gravity of the View or Layout relative to its parent. - arranges the view's position outside of itself. -------------------------------------------------------------- HTML/CSS Equivalents: Android CSS android:layout_gravity float android:gravity text-align

+ Retrofit (May 25, 2019, 9:23 a.m.)

1- Create an Interface: that will contain various functions which will map to the endpoint URLs of your web service, such as: getStudents() deleteStudent() 2- Create a service that calls the functions present within the interface. createService( <T> Service) -> studentsService 3- Last step, within your activity, you have to initialize the step-2 service and then call the functions of the interface in step-1. destinationService.getDestination()

+ Shared Preferences (May 13, 2019, 11:24 p.m.)

It allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application. Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.getDataDirectory(). ------------------------------------------------------------ SharedPreferences is application specific, i.e. the data is lost on performing one of the following options: - on uninstalling the application - on clearing the application data (through Settings) ------------------------------------------------------------ As the name suggests, the primary purpose is to store user-specified configuration details, such as user specific settings, keeping the user logged into the application. ------------------------------------------------------------ To get access to the preferences, we have three APIs to choose from: - getPreferences() : used from within your Activity, to access activity-specific preferences - getSharedPreferences() : used from within your Activity (or other application Context), to access application-level preferences - getDefaultSharedPreferences() : used on the PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference framework ------------------------------------------------------------ // Storing Data: sharedPref = getSharedPreferences(getString(R.string.preference_file_key), MODE_PRIVATE) with(sharedPref.edit()) { putBoolean("intro_screen_displayed", true) apply() } // Retrieving Data var sharedPref = getSharedPreferences(getString(R.string.preference_file_key), MODE_PRIVATE) if (sharedPref.getBoolean("intro_screen_displayed", false)) startActivity(mainActivity) ------------------------------------------------------------ editor.putBoolean("key_name", true); // Storing boolean - true/false editor.putString("key_name", "string value"); // Storing string editor.putInt("key_name", "int value"); // Storing integer editor.putFloat("key_name", "float value"); // Storing float editor.putLong("key_name", "long value"); // Storing long pref.getString("key_name", null); // getting String pref.getInt("key_name", -1); // getting Integer pref.getFloat("key_name", null); // getting Float pref.getLong("key_name", null); // getting Long pref.getBoolean("key_name", null); // getting boolean ------------------------------------------------------------ // Clearing or Deleting Data: remove(“key_name”) is used to delete that particular value. clear() is used to remove all data ------------------------------------------------------------

+ Repeat background image (May 11, 2019, 8:41 p.m.)

1- Copy the background image in drawable 2- Create a file in drawable "bg_pattern.xml" with this content: <bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/bg" android:tileMode="repeat" /> 3- Add the following attribute to the XML file for the specific view: android:background="@drawable/bg_pattern"

+ Get asset image by its string name (May 11, 2019, 2:47 p.m.)

import android.graphics.BitmapFactory import android.graphics.Bitmap var icon: Bitmap? = BitmapFactory.decodeStream(assets.open("intro_screen/img1.jpg")) icon.setImageBitmap(icon)

+ dimensions (May 10, 2019, 8:21 p.m.)

xxxhdpi: 1280x1920 px xxhdpi: 960x1600 px xhdpi: 640x960 px hdpi: 480x800 px mdpi: 320x480 px ldpi: 240x320 px

+ mipmap directories (May 10, 2019, 8:10 p.m.)

Like all other bitmap assets, you need to provide density-specific versions of you app icon. However, some app launchers display your app icon as much as 25% larger than what's called for by the device's density bucket. For example, if a device's density bucket is xxhdpi and the largest app icon you provide is in drawable-xxhdpi, the launcher app scales up this icon, and that makes it appear less crisp. So you should provide an even higher density launcher icon in the mipmap-xxxhdpi directory. Now the launcher can use the xxxhdpi asset instead. Because your app icon might be scaled up like this, you should put all your app icons in mipmap directories instead of drawable directories. Unlike the drawable directory, all mipmap directories are retained in the APK even if you build density-specific APKs. This allows launcher apps to pick the best resolution icon to display on the home screen.

+ Configuration qualifiers for different pixel densities (May 10, 2019, 8:01 p.m.)

ldpi Resources for low-density (ldpi) screens (~120dpi). mdpi Resources for medium-density (mdpi) screens (~160dpi). (This is the baseline density.) hdpi Resources for high-density (hdpi) screens (~240dpi). xhdpi Resources for extra-high-density (xhdpi) screens (~320dpi). xxhdpi Resources for extra-extra-high-density (xxhdpi) screens (~480dpi). xxxhdpi Resources for extra-extra-extra-high-density (xxxhdpi) uses (~640dpi). nodpi Resources for all densities. These are density-independent resources. The system does not scale resources tagged with this qualifier, regardless of the current screen's density. tvdpi Resources for screens somewhere between mdpi and hdpi; approximately 213dpi. This is not considered a "primary" density group. It is mostly intended for televisions and most apps shouldn't need it—providing mdpi and hdpi resources is sufficient for most apps and the system will scale them as appropriate. If you find it necessary to provide tvdpi resources, you should size them at a factor of 1.33*mdpi. For example, a 100px x 100px image for mdpi screens should be 133px x 133px for tvdpi.

+ ConstraintLayout (March 24, 2019, 12:15 p.m.)

Constraints help us to describe what are relations of views. ----------------------------------------------------------------- A constraint is a connection or an alignment to the element the constraint is tied to. You define various constraints for every child view relative to other views present. This gives you the ability to construct complex layouts with a flat view hierarchy. A constraint is simply a relationship between two components within the layout that controls how the view will be positioned. ----------------------------------------------------------------- The ConstraintLayout system has three parts: constraints, equations, and solver. Constraints are relationships between your views and are determined when you set up your UI. Once you create these relationships, the system will translate them into a linear system of equations. The equations go in the solver and it returns the positions, and view sizes to be used in the layout. ----------------------------------------------------------------- The ConstraintLayout becomes very necessary most especially when building complex layouts. Android actually has other layouts, which have their own unique features. Some of which could be used to build complex layouts also. However, they have their own bottlenecks, hence the need to introduce a new layout. These older layouts have rules that tend to be too rigid. As a result of this, the tendency to nest layouts become higher. For instance, the LinearLayout only permits placing views linearly, either horizontally or vertically. The FrameLayout places views in a stacked manner, the topmost view hides the rest. The RelativeLayout places the views relative to each other. ----------------------------------------------------------------- When creating constraints, there are a few rules to follow: Every view must have at least two constraints: one horizontal and one vertical. If a constraint for any axis is not added, your view jumps to the zero point of that axis. You can create constraints only between a constraint handle and an anchor point that share the same plane. So a vertical plane (the left and right sides) of a view can be constrained only to another vertical plane, and baselines can constrain only to other baselines. Each constraint handle can be used for just one constraint, but you can create multiple constraints (from different views) to the same anchor point. -----------------------------------------------------------------

+ Custom font (April 26, 2019, 9:16 p.m.)

https://medium.com/@studymongolian/using-a-custom-font-in-your-android-app-cc4344b977a5

+ Creating actions in the action bar / toolbar (April 25, 2019, 11:10 p.m.)

https://developer.android.com/training/appbar/actions -------------------------------------------------------------------- Buttons in the toolbar are typically called actions. Space in the app bar is limited. If an app declares more actions than can fit in the app bar, the app bar sends the excess actions to an overflow menu. The app can also specify that an action should always be shown in the overflow menu, instead of being displayed on the app bar. -------------------------------------------------------------------- Add Action Buttons: All action buttons and other items available in the action overflow are defined in an XML menu resource. To add actions to the action bar, create a new XML file in your project's res/menu/ directory as follows: 1- In Android Studio, in project view, select "Project", right click on "res" folder and choose the menu "New" -> "Android Resource File". 2- In the window for "file name" set for example "main_toolbar" and for "Resource type" choose "menu", hit OK button. 3- Add an <item> element for each item you want to include in the action bar, as shown in this code example of a menu XML file: <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_favorite" android:icon="@drawable/ic_favorite_black_48dp" android:title="@string/action_favorite" app:showAsAction="ifRoom"/> <!-- Settings, should always be in the overflow --> <item android:id="@+id/action_settings" android:title="@string/action_settings" app:showAsAction="never"/> </menu> 4- Add the following code to MainActivity.kt override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main_toolbar, menu) return true } // This is to only display where the above code should be placed. override fun onCreate(savedInstanceState: Bundle?) { }

+ Set up the app bar (Toolbar) (April 25, 2019, 10:50 p.m.)

https://developer.android.com/training/appbar/setting-up#kotlin ------------------------------------------------------------------------------- 1- Replace android:theme="@style/AppTheme" with android:theme="@style/Theme.AppCompat.Light.NoActionBar" in AndroidManifest.xml 2- Add a Toolbar to the activity's layout (activity_main.xml) <android.support.v7.widget.Toolbar android:id="@+id/my_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:elevation="4dp" android:theme="@style/ThemeOverlay.AppCompat.ActionBar" app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/> It might display an error about "This view is not constrained vertically...", for fixing the error: Go to Design View, use the magic wand icon in the toolbar menu above the design preview. This will automatically add some lines in the text field and the red line will be removed. You can also set the background color to transparent: android:background="@android:color/transparent"; 3- Add the 3rd line to MainActivity.kt super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(findViewById(R.id.my_toolbar))

+ Views (April 25, 2019, 12:22 p.m.)

A view is basically any of the widgets that make up a typical utility app. Examples include images (ImageViews), text (TextView), editable text boxes (EditText), web pages (WebViews), and buttons (err, Button).

+ XML - Introduction (April 25, 2019, 12:14 p.m.)

XML describes the views in your activities, and Kotlin tells them how to behave. Sometimes XML will be used to describe types of data other than views in your apps; acting as a kind of index that your code can refer to. This is how most apps will define their color palettes for instance, meaning that there’s just one file you need to edit if you want to change the look of your entire app.