- View Binding in Android
- Getting started with View Binding
- Using View Binding in Fragments
- Start using View Binding
- One-Liner ViewBinding Library
- Доступ к View внутри фрагмента
- Доступ к View внутри динамического фрагмента из активности
- res/layout/fragmentlayout.xml
- Передача данных между фрагментами
- res/layout/redfragment.xml
- res/layout/bluefragment.xml
- Cardview with Recyclerview Android Example [beginners]
- Cardview XML attribute
- Cardview android example with Recyclerview
- Step 1 — Adding dependencies
- IView Parent Interface
- Definition
- Remarks
- Properties
- Methods
- Extension Methods
- Save data in a local database using Room Part of Android Jetpack.
- Setup
- Groovy
- Kotlin
- Primary components
- Sample implementation
- Data entity
- Kotlin
- Data access object (DAO)
- Kotlin
- Database
- Kotlin
- Usage
- Kotlin
- Kotlin
- Additional resources
- Sample
- Codelabs
- Blogs
View Binding in Android
We have learnt that every time we need to access a view from our XML layout into our Java or Kotlin code, we must use findViewById(). It was okay for small/personal projects where we use 5 to 6 views in a layout. But for larger projects we have comparatively more views in a layout, and accessing each view using the same findViewById() is not really comfortable.
What is View Binding?
View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module
Simply put, this allows us to access the views from the layout file in a very simple way by linking variables of our Kotlin or Java code with the XML views. When a layout is inflated, it creates a Binding object, which contains all the XML views that are casted to the correct type. This makes it really easier for us since we can retrieve all views in one line of code.
Getting started with View Binding
- Let’s start by enabling view binding in our project:
In build.gradle(:app) add the code in -> android
2. Before the onCreate() method, we create our binding object
3. Perform the following steps in onCreate() method:
- Call the inflate() method to create an instance of the binding class for the activity to use.
- Get reference to the root view
- Pass the root view to setContentView() [setContentView(binding.root)] instead of layout [setContentView(R.id.activity_main)]
4. To get reference of any view, we can use the binding object:
Using View Binding in Fragments
We follow the same steps:
- Before the onCreateView() method, we create our binding object
2. Initialize our binding object in onCreateView()
3. To get reference of any view, we can use the binding object
Note: The name of the binding class is generated by converting the name of the XML file to camel case and adding the word “Binding” to the end. Similarly, the reference for each view is generated by removing underscores and converting the view name to camel case . For example, activity_main.xml becomes ActivityMainBinding, and you can access @id/text_view as binding.textView.
View binding has important advantages over using findViewById():
- Null safety: Since view binding creates direct references to views, there’s no risk of a null pointer exception due to an invalid view ID.
- Type safety: The fields in each binding class have types matching the views they reference in the XML file. This means that there’s no risk of a class cast exception.
Start using View Binding
If you’re intrigued by View Binding and want to learn more about it, here’s some resources for you to learn:
One-Liner ViewBinding Library
You would have noticed that to use View Binding, we need to call the static inflate() method included in the generated binding class ( which creates an instance of the binding class for the activity or fragment )
Yesterday I came across an awesome library that makes ViewBinding one-liner ( By removing the boilerplate code and easily set ViewBindings with a single line )
One-liner ViewBinding Library : [Click Here]
Источник
Доступ к View внутри фрагмента
Так как существует два способа использования фрагментов в активности, то взаимодействие между компонентами, которые находятся внутри фрагментов немного отличается.
Доступ к View внутри динамического фрагмента из активности
Рассмотрим пример доступа к компоненту, который находится внутри динамического фрагмента из активности.
Фрагмент может иметь собственную разметку и содержать различные компоненты View: TextView, EditText и т.д. Напрямую из активности обратиться к нужному компоненту и поменять, например, текст в TextView не получится. А как же достучаться до нужного компонента? Рассмотрим простой пример.
Создадим класс фрагмента MyFragment.java:
В методе onCreateView() мы указали ресурс разметки R.layout.fragmentlayout. Давайте создадим разметку для фрагмента.
res/layout/fragmentlayout.xml
В данной разметке нас интересует вторая текстовая метка с идентификатором fragmenttext.
Создадим разметку для основной активности:
Последняя компоновка LinearLayout с идентификатором myfragment является контейнером для фрагмента, который будет его замещать. Напишем код для главной активности:
При запуске программы мы получаем экземпляр класса FragmentTransaction и добавляем фрагмент на экран вместо LinearLayout. Теперь текстовая метка фрагмента доступна для изменения — получаем ссылку на нужный компонент и устанавливаем требуемый текст.
Передача данных между фрагментами
Когда мы заменяем контейнер своим фрагментом, то он становится частью активности и получаем доступ к компонентам стандартным способом, как в примере выше. Если мы используем фрагменты как самостоятельные элементы, то доступ к компонентам происходит немного по-другому. Так как фрагменты не существуют сами по себе, а только внутри активности, то сначала нужно получить доступ к родительской активности через метод getActivity(), а затем уже можно получить доступ к нужному компоненту из фрагмента:
Создадим разметки для двух фрагментов. В одном разместим текстовое поле, а во втором кнопку и текстовую метку, в которой будем выводить текст из текстового поля первого фрагмента:
res/layout/redfragment.xml
res/layout/bluefragment.xml
В код первого фрагмента добавим только наполнение из разметки:
В класс второго фрагмента добавим код для чтения данных из первого фрагмента. Сделаем это в методе onStart():
Мы получаем ссылки на все компоненты и обрабатываем щелчок мыши. В разметку активности добавьте два созданных фрагмента и запустите пример. Введите какой-нибудь текст в текстовом поле (напоминаю, что он относится к первому фрагменту). Нажмите на кнопку, которая относится ко второму фрагменту. В текстовой метке второго фрагмента появится введённым вами текст.
Источник
Cardview with Recyclerview Android Example [beginners]
Cardview Android is a new widget for Android, which can be used to display a card sort of a layout in android. Cardview was introduced in Material Design in API level 21 (Android 5.0 i.e Lollipop).
Since, Cardview is part of material design.It’s such a view which has all material design properties, most importantly showing shadows according to the elevation.
The best part about this view is that it extends FrameLayout and it can be displayed on all the platforms of Android since it’s available through the Support v7 library.
The design of the cardview will be looks like,
In the above picture, every boxes made with cardview in android.
Before jumping into the coding part, Let’s see the Cardview XML attribute, that makes the cardview looks beautiful.
Cardview XML attribute
CardView_cardBackgroundColor : ColorStateList: The new ColorStateList to set for the card background
CardView_cardCornerRadius : float: The radius in pixels of the corners of the rectangle shape
CardView_cardElevation : float: The backward compatible elevation in pixels.
CardView_cardMaxElevation : float: The backward compatible maximum elevation in pixels.
CardView_cardPreventCornerOverlap : boolean: Whether CardView should add extra padding to content to avoid overlaps with the CardView corners.
CardView_cardUseCompatPadding : boolean: true> if CardView should add padding for the shadows on platforms Lollipop and above.
CardView_contentPadding : Sets the padding between the Card’s edges and the children of CardView.
CardView_contentPaddingBottom : int: The bottom padding in pixels
CardView_contentPaddingLeft : int: The left padding in pixels
CardView_contentPaddingRight : int: The right padding in pixels
Done with explanation about the android cardview. Let get into the coding part.
Cardview android example with Recyclerview
In this post, I am going to create cardview with recyclerview in android to list the movies with the image and the movie title.
example application demo,
Step 1 — Adding dependencies
In this example, I am using recyclerview with cardview. But I am not going deeper into recyclerview. I am already have a post on recyclerview in android.
Источник
IView Parent Interface
Definition
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Defines the responsibilities for a class that will be a parent of a View.
Remarks
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Properties
Gets the JNI value of the underlying Android object.
(Inherited from IJavaObject)
Tells if this view parent layout direction is resolved.
Indicates whether layout was requested on this view parent.
Tells if this view parent text alignment is resolved.
Tells if this view parent text direction is resolved.
Return this view parent layout direction.
Returns the parent if it exists, or null.
Gets the parent of a given View for accessibility.
Return this view parent text alignment.
Return this view parent text direction.
Methods
Change the z order of the child so it’s on top of all other children.
Tells if this view parent can resolve the layout direction.
Tells if this view parent can resolve the text alignment.
Tells if this view parent can resolve the text direction.
This method is called on the parent when a child’s drawable state has changed.
Called when a child view now has or no longer is tracking transient state.
Called when a child of this parent is giving up focus
Have the parent populate the specified context menu if it has anything to add (and then recurse on its parent).
Tells the parent that a new focusable view has become available.
Find the nearest view in the specified direction that wants to take focus
Compute the visible part of a rectangular region defined in terms of a child view’s coordinates.
All or part of a child is dirty and needs to be redrawn.
All or part of a child is dirty and needs to be redrawn.
Find the nearest keyboard navigation cluster in the specified direction.
Notifies a view parent that the accessibility state of one of its descendants has changed and that the structure of the subtree is different.
The target View has been invalidated, or has had a drawing property changed that requires the hierarchy to re-render.
Request a fling from a nested scroll.
React to a nested fling before the target view consumes it.
React to an accessibility action delegated by a target descendant view before the target processes it.
React to a nested scroll in progress before the target view consumes a portion of the scroll.
React to a nested scroll in progress.
React to the successful claiming of a nested scroll operation.
React to a descendant view initiating a nestable scroll operation, claiming the nested scroll operation if appropriate.
React to a nested scroll operation ending.
Tell view hierarchy that the global view attributes need to be re-evaluated.
Called when a child of this parent wants focus
Called when a child of this group wants a particular rectangle to be positioned onto the screen.
Called when a child does not want this parent and its ancestors to intercept touch events with ViewGroup#onInterceptTouchEvent(MotionEvent) .
Ask that a new dispatch of View#fitSystemWindows(Rect) View.fitSystemWindows(Rect) be performed.
Called when something has changed which has invalidated the layout of a child of this view parent.
Called by a child to request from its parent to send an AccessibilityEvent .
Called when a child wants the view hierarchy to gather and report transparent regions to the window compositor.
Shows the context menu for the specified view or its ancestors.
Shows the context menu for the specified view or its ancestors.
Start an action mode for the specified view with the default type ActionMode#TYPE_PRIMARY .
Start an action mode for the specified view with the default type ActionMode#TYPE_PRIMARY .
Extension Methods
Performs an Android runtime-checked type conversion.
Источник
Save data in a local database using Room Part of Android Jetpack.
Apps that handle non-trivial amounts of structured data can benefit greatly from persisting that data locally. The most common use case is to cache relevant pieces of data so that when the device cannot access the network, the user can still browse that content while they are offline.
The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In particular, Room provides the following benefits:
- Compile-time verification of SQL queries.
- Convenience annotations that minimize repetitive and error-prone boilerplate code.
- Streamlined database migration paths.
Because of these considerations, we highly recommend that you use Room instead of using the SQLite APIs directly.
Setup
To use Room in your app, add the following dependencies to your app’s build.gradle file:
Groovy
Kotlin
Primary components
There are three major components in Room:
- The database class that holds the database and serves as the main access point for the underlying connection to your app’s persisted data.
- Data entities that represent tables in your app’s database.
- Data access objects (DAOs) that provide methods that your app can use to query, update, insert, and delete data in the database.
The database class provides your app with instances of the DAOs associated with that database. In turn, the app can use the DAOs to retrieve data from the database as instances of the associated data entity objects. The app can also use the defined data entities to update rows from the corresponding tables, or to create new rows for insertion. Figure 1 illustrates the relationship between the different components of Room.
Figure 1. Diagram of Room library architecture.
Sample implementation
This section presents an example implementation of a Room database with a single data entity and a single DAO.
Data entity
The following code defines a User data entity. Each instance of User represents a row in a user table in the app’s database.
Kotlin
To learn more about data entities in Room, see Defining data using Room entities.
Data access object (DAO)
The following code defines a DAO called UserDao . UserDao provides the methods that the rest of the app uses to interact with data in the user table.
Kotlin
Database
The following code defines an AppDatabase class to hold the database. AppDatabase defines the database configuration and serves as the app’s main access point to the persisted data. The database class must satisfy the following conditions:
- The class must be annotated with a @Database annotation that includes an entities array that lists all of the data entities associated with the database.
- The class must be an abstract class that extends RoomDatabase .
- For each DAO class that is associated with the database, the database class must define an abstract method that has zero arguments and returns an instance of the DAO class.
Kotlin
Note: If your app runs in a single process, you should follow the singleton design pattern when instantiating an AppDatabase object. Each RoomDatabase instance is fairly expensive, and you rarely need access to multiple instances within a single process.
If your app runs in multiple processes, include enableMultiInstanceInvalidation() in your database builder invocation. That way, when you have an instance of AppDatabase in each process, you can invalidate the shared database file in one process, and this invalidation automatically propagates to the instances of AppDatabase within other processes.
Usage
After you have defined the data entity, the DAO, and the database object, you can use the following code to create an instance of the database:
Kotlin
You can then use the abstract methods from the AppDatabase to get an instance of the DAO. In turn, you can use the methods from the DAO instance to interact with the database:
Kotlin
Additional resources
To learn more about Room, see the following additional resources:
Sample
- Android Sunflower, a gardening app that illustrates Android development best practices with Android Jetpack.
- Tivi, a TV show tracking app that uses the latest libraries and tools.
Codelabs
Blogs
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Источник