Skip to main content

Posts

Showing posts with the label CardView

Android Kotlin: How to set CardView elevation

This code demonstrates setting the elevation of a CardView programmatically in an Android application written with Kotlin. It achieves this by defining an extension function and utilizing properties available on the CardView class. Explanation: MainActivity.kt: The onCreate function inflates the layout ( activity_main.xml ) and sets the content view. It retrieves a reference to the second CardView ( cardViewBottom ) using its ID. The code then sets the elevation property of the card to 4dp using the dpToPixels extension function. This function converts the provided dp value (density-independent pixels) to the equivalent pixel size based on the device's display metrics. Finally, the maxCardElevation property is set to 6dp, defining the maximum elevation the card can reach when pressed. Extension function - dpToPixels: This extension function takes an integer representing dp and the context of the application as arguments. It uses TypedValue.applyDimension to convert th...

Android Kotlin: How to set CardView background color

Android Kotlin: Setting CardView Background Color This code demonstrates how to set the background color of a CardView programmatically in an Android application written in Kotlin. It utilizes two approaches: defining the color in the layout file (XML) and setting it dynamically in code. The code consists of three main parts: MainActivity.kt: This file contains the main activity class that manages the UI. It inflates the layout ( activity_main.xml ) and sets the background color of the second CardView programmatically in the onCreate method. activity_main.xml: This file defines the layout of the activity. It includes two CardViews stacked on top of each other. The first card has its background color defined directly in the XML using the app:cardBackgroundColor attribute. The second card has the same attributes defined except for the background color. build.gradle(app): (Code not provided) This file specifies the project's dependencies. It includes the androidx.card...