Mobile Programming Class Rules and Course Assessment PDF

Summary

These lecture notes cover the fundamentals of mobile programming, including class rules, course assessment details, and a brief introduction to mobile devices and their operating systems. The document details some specifics of Mobile App Development and Mobile Operating Systems

Full Transcript

10/18/2024 Mobile Programming 1 Class Rules You can do anything except: Make noises (chatting, singing…) Feel free to interrupt me if you have questions. According to the university policy, taking attendance is needed. Important: you...

10/18/2024 Mobile Programming 1 Class Rules You can do anything except: Make noises (chatting, singing…) Feel free to interrupt me if you have questions. According to the university policy, taking attendance is needed. Important: you are required to have an 80% attendance to be able to seat for the final exam. 2 2 1 10/18/2024 Course Assessment  Temporary according to the situation:  Final exam:50%  Midterm: 20%,  Quizzes: 10%  Project: 20%, 2-3 members per group; report and presentation are required.  Important:cheating and plagiarism will get no marks. 3 3 A few suggestions…. Your final grade is based on points – not on an accumulation of grades. You start the class with zero points and earn your way to your final grade If you have an issue or problem, communicate – send me an email If you know you’re not going to meet the deadline for a quiz or assignment – email me BEFORE the deadline 4 4 2 10/18/2024 WHAT IS A MOBILE DEVICE? A mobile device is a portable handheld computer designed to connect to the Internet. It is easy and quick to use and can be taken and used everywhere at any time. Some mobile devices are more powerful than others, which allows users to do many things that can be done with a desktop or laptop computer. The primary mobile devices currently available are: Tablet computers, E-readers, Smartphones 5 What is Mobile Application Development? Mobile app development refers to creating software applications that run on mobile devices such as smartphones and tablets. The software can be designed for various operating systems (OS), such as Android, iOS, or others. 6 3 10/18/2024 Types of Mobile Applications Native Apps: Explicitly built for a particular operating system (e.g., Android, iOS) using platform-specific languages like Java/Kotlin for Android and Swift/Objective C for iOS. These apps are installed directly from app stores and can leverage all device- specific features. Hybrid Apps: These are cross-platform apps developed using web technologies (HTML, CSS, JavaScript) and frameworks like React Native, Ionic, and Cordova. They are essentially web apps wrapped in a native container, allowing them to be installed like native apps. Web Apps: Brows-based apps accessed through mobile browsers (e.g., Progressive Web Apps PWAs). These do not require installation but provide limited access to device hardware. 7 Mobile Platforms Android: Developed by Google, it is the world’s most widely used mobile OS. It is written in Java, Kotlin, and C++ and has an open ecosystem. iOS: Apple’s proprietary OS for iPhones and iPads. It is known for its security, smooth user experience, and strict app store guidelines. Other platforms : Windows Mobile and Blackberry have largely been phased out, but their legacy and influence on mobile development are worth mentioning. 8 4 10/18/2024 Mobile Operating Systems 1. Palm OS 2. WML 3. J2ME/JME (Java 2 Platform, Micro Edition) 4. Windows 5. Android 6. IOS 9 ANDROID Google formed the Open Handset Alliance with 86 hardware, software, and telecom companies, which developed and announced Android as an open-source mobile OS. It has been used as the OS for mobile devices such as tablets and smartphones. This OS is now being used by many handheld device manufacturers including Samsung, Motorola, HTC, LG and Sony. 10 5 10/18/2024 ANDROID PROS You can develop on any platform. The environment is more open: call history is available to all apps; notifications between apps and content sharing are possible; apps can be installed from any source. Apps can be self-signed. You can publish to Google Play for a one-off fee of $25. 11 ANDROID CONS Fragmentation between different versions of the OS, which are often significantly different, is a significant problem. Upgrades are passed through manufacturers and carriers who add their customizations, delaying the process. App developers must try accommodating users whose OS versions are years apart. Graphics are often slower. 12 6 10/18/2024 IOS iPhone OS is based on Unix OS and was renamed ‘iOS,’ released in 2007. Apple initially developed this OS for the iPhone and later extended it to iPad, iPod Touch, and Apple TV. It consists of four layers, namely the Core OS layer, the Core Services layer, the Media layer, and the Cocoa Touch layer. The iOS user interface is based on a multitouch gesture concept. 13 IOS PROS Less fragmentation arising from upgrades – 80% of users are on the latest version. New features are usually available very quickly. The OpenGL API is standard for graphics across the platform. Navigation is nonprescriptive–you can decide how users will navigate within your app. 14 7 10/18/2024 IOS CONS iOS is a more closed platform with limited possibilities for inter-app communication. The App Store automatically rejects private APIs. Development can only be done on a Mac. To publish apps, you need to subscribe to the iOS developer program (annual fee), and the intricate App Store guidelines will keep you engaged. The process of signing apps is nontrivial. You need an Apple certificate to install it on your device. 15 App Stores & Monetization Google Play Store and Apple App Store are the two dominant platforms for app distribution. Monetization models: Free apps with ads (popular in Android due to user demographics). Freemium apps: free to download but with in-app purchases (common in games and subscription-based apps). Paid apps: Less common, especially on Android. Subscriptions: A growing trend, especially for media, content, or service apps (e.g., Netflix, Spotify, news apps). 16 8 10/18/2024 Mobile App Development Lifecycle Ideation & Planning Design (UI/UX) Development Testing Deployment Maintenance 17 Programming Languages for Mobile Development Java Swift JavaScript Dart 18 9 10/18/2024 Mobile Development Frameworks Android Studio: Official integrated development environment (IDE) for Android. It offers a built-in emulator, code editing, and testing tools. Xcode: Apple’s official IDE for iOS/macOS development. It includes an interface builder, testing, and debugging tools. React Native: Enables building cross platform apps using JavaScript. Allows for faster development since you write the code once and run it on both Android and iOS. Flutter: Google’s cross-platform UI toolkit that allows you to create natively compiled apps for mobile, web, and desktop from a single codebase. It uses widgets and is highly customizable. 19 Mobile App Architecture MVC (Model-View-Controller) Architecture MVVM (Model-View-ViewModel) Architecture Clean Architecture 20 10 10/18/2024 MVC Architecture 21 MVC Architecture Model (Data and Business Logic): Manages the data and business logic of the application. Represents the state of the app, independent of the UI. Updates the controller when data changes. 22 11 10/18/2024 MVC Architecture View (User Interface) The user interface (UI) component that represents the data. It displays the model’s data and handles what the user sees. Receives updates from the controller when data changes. 23 MVC Architecture Controller (Application Logic) The intermediary between the model and the view. It processes user input (e.g., taps, gestures) and translates it into actions that update the model or view. Controls the flow of data to the view. 24 12 10/18/2024 Advantages of MVC Separation of Concerns. Reusability Maintainability Testability 25 Disadvantages of MVC Architecture Increased Complexity Tight Coupling Between View and Controller: 26 13 10/18/2024 Example Scenario in an E-Commerce App (MVC Implementation) 1. Model: 1. Holds the data about products (name, price, description, etc.). 2. Contains the business logic for adding items to the cart or applying discounts. 2. View: 1. Displays the product list, cart summary, and purchase button to the user. 2. Shows dynamic changes when new items are added to the cart or removed. 3. Controller: 1. Listens for the user clicking the "Add to Cart" button. 2. Updates the Model to reflect the new item in the cart. 3. Instructs the View to update and show the new item count and price. 27 MVVM Architecture 28 14 10/18/2024 MVVM Architecture Model (Data and Business Logic) Manages the app’s data and business logic, similar to MVC. Data is fetched from the database, API, or any other source. 29 MVVM Architecture View (User Interface): The UI layer of the app represents the data to the user. It is passive in MVVM, meaning it doesn’t contain any business logic and observes the ViewModel. 30 15 10/18/2024 MVVM Architecture ViewModel (Presentation Logic): Acts as a bridge between the View and the Model. Responsible for handling the presentation logic and interacting with the Model to fetch and manage data. 31 Advantages of MVVM Architecture Separation of Concerns Two-Way Data Binding Testability Reusable Components Reduced Code in View 32 16 10/18/2024 Disadvantages of MVVM Architecture Complexity Learning Curve Overhead for Small Apps 33 Example Scenario in a Weather App (MVVM Implementation) 1. Model: 1. Fetches weather data from an API (e.g., temperature, conditions). 2. Stores the fetched data in a local cache or database for offline use. 2. ViewModel: 1. Retrieves the weather data from the Model. 2. Formats the weather data for display (e.g., converting temperatures, formatting dates). 3. Exposes the weather data through observable properties for the View to bind to. 3. View: 1. Displays the weather data, such as the current temperature and forecast. 2. Automatically updates when the ViewModel’s weather data changes (e.g., after a new API request). 3. Allows the user to trigger actions like refreshing the weather data or changing location settings. 34 17 10/18/2024 Clean Architecture 35 Clean Architecture Entities (Domain Layer): The innermost layer of the application. Contains the core business logic and rules, independent of any UI or data source. Highly reusable across different parts of the app and easily testable. 36 18 10/18/2024 Clean Architecture Use Cases (Application Layer): This layer contains the specific application logic (interactors). It defines how the business rules interact with one another. Use cases to orchestrate the data flow between the UI and the Entities. 37 Clean Architecture Interface Adapters (Presentation Layer): The layer where ViewModels, Presenters, or Controllers reside. It transforms and prepares the data from the Use Cases for display in the View. Keep the UI separate from the underlying data sources and business logic. 38 19 10/18/2024 Clean Architecture Frameworks & Drivers (Infrastructure Layer): The outermost layer of Clean Architecture. It includes implementing data sources (APIs, databases), frameworks, and UI. This layer should depend on the inner layers, not the other way around (inversion of control principle). 39 Advantages of Clean Architecture Separation of Concerns Testability Scalability 40 20 10/18/2024 Disadvantages of Clean Architecture Complexity Learning Curve More Code 41 Example Scenario in an E-Commerce App (Clean Architecture Implementation) Entity: A Product entity with attributes such as id, name, price, stock, and methods like applyDiscount(). Use Case: AddProductToCart interacts with the Product entity to check stock and calculate the total price. It also prepares the cart for checkout by updating the repository. Interface Adapter: Controller captures the "Add to Cart" button press from the UI and triggers the AddProductToCart use case. Presenter prepares the cart’s total price and product information to display in the UI. Frameworks & Drivers: The UI Framework (e.g., Android/iOS) displays the updated cart. A Database stores the cart’s content for persistence. 42 21 10/18/2024 Good Practices UI/UX in Mobile Apps Mobile App Performance Optimization Security in Mobile Applications Testing Mobile Applications Deploying and Publishing Mobile Apps 43 Attendance 44 22 10/18/2024 Attendance 45 23 10/30/2024 Fundamentals of Mobile Computing 1 What is Mobile Computing? Mobile computing refers to the ability to access and process information on portable devices without being restricted by location. 2 1 10/30/2024 Mobile Computing Features Mobility, connectivity, Real-time access to information, and wireless communication. 3 Mobility in Cellular Communication Mobility: The defining feature of mobile computing. Handoff Process: The seamless transition from one cell tower to another as users move between cells. Continuous Service: Ensuring uninterrupted connection as the user moves through different areas. 4 2 10/30/2024 Feature of Mobile Computing 1. Portability: Devices should be portable, lightweight, and capable of operating without constant power. 2. Connectivity: The network should be reliable with minimal downtime, even as devices move. 3. Interactivity: Devices should communicate efficiently with other nodes in the system. 4. Individuality: Mobile systems should cater to personal user needs (custom apps, personalized notifications). 5 Network Design for Mobile Computing Wireless Application Protocol (WAP) WAP was a stripped-down version of HTTP, a basic protocol and the foundation of data communication on the World Wide Web (WWW). Also, applications were developed using an XML-based Wireless Markup Language (WML), which the WAP Forum invented for use with WAP 6 3 10/30/2024 Network Design for Mobile Computing WAP did not meet the commercial expectations for several reasons, such as: WAP browsers, with their slow speed. They did not support the user experience, especially on small screens that were too small to allow surfing on the web. Also, reading a sentence fragment at a time and then waiting seconds for the next segment to download created criticism amongst users who labeled WAP services as ‘Wait and Pay.’. 7 Network Design for Mobile Computing Wireless LAN Design Considerations: Factors like user traffic, the number of devices, location of access points, and interference. Wide Area Radio Networks: Challenges of building and integrating a private radio network with an existing infrastructure. Ensuring minimal dead spots and maximizing coverage. 8 4 10/30/2024 Advantages of Cellular Networks Scalability: Add more towers to extend coverage and improve service. Lower Power Consumption: Devices use less energy when connecting to nearby towers than a central transmitter. 9 Mobile Computing Devices Netbooks: Small, lightweight laptops with essential processing power. Cell Phones: Early mobile phones versus modern smartphones, focusing on technological advancements. Smartphones: Powerful handheld computers capable of running apps, connecting to the internet, and more. Smart Pads: Devices with advanced touchpad technology that allow multi-finger gestures. 10 5 10/30/2024 Mobile Application Design challenges Technical Data Security: Design: Compression: Managing Reducing the Protecting data network data sent over from capacity, the network to unauthorized response time, maximize access through and system bandwidth encryption and availability. usage. firewalls. 11 How would you ensure the mobile app is fast, secure, and efficient? Data Caching Minimize Network Requests Lightweight Design Data Encryption Authentication Regular Updates Battery and Resource Management 12 6 10/30/2024 Limitations of Mobile Computing Range and Bandwidth Limitations: Mobile internet speeds are slower compared to wired connections. Security Concerns: Mobile devices are vulnerable to security breaches when using public networks. Power Consumption: Mobile devices are constrained by battery life, which can be problematic in power- intensive tasks. Interference: Terrain, weather, and distance from a cell tower can interfere with signal quality. 13 The Future of Mobile Computing 5G Networks AI in Mobile Devices Wearable Technology 14 7 10/30/2024 How will mobile computing utilize AI, 5G, or wearables to transform the healthcare, and entertainment industries? Healthcare AI: Enhances diagnostics with AI-powered image analysis, personalized treatment plans, and predictive analytics for patient care. 5G: Enables real-time remote surgeries, telemedicine, and faster patient monitoring and health records data transfer. Wearables: Continuous health tracking for vital signs, early detection of medical conditions, and improved patient engagement through personalized insights. 15 How will mobile computing utilize AI, 5G, or wearables to transform the healthcare and entertainment industries? Entertainment AI: Delivers personalized content recommendations, AI-generated media, and immersive experiences using virtual reality (VR) and augmented reality (AR). 5G: Supports high-quality streaming with ultra-low latency, interactive live events, and seamless gaming experiences. Wearables: Enhances interactive experiences with AR/VR headsets and wearable devices, creating immersive entertainment and gaming experiences. 16 8 10/30/2024 Mobile Application Development 17 Device Fragmentation Challenges Device fragmentation refers to the wide variety of mobile devices in the market, each with different screen sizes, resolutions, hardware capabilities, and operating system (OS) versions. This variety makes it challenging for developers to create an app that works seamlessly across all devices without significant adaptations. 18 9 10/30/2024 Feature in Device Fragmentation Screen Sizes and Aspect Ratios Hardware Capabilities Operating System 19 Challenges Developers Face Due to Fragmentation 1. UI/UX Design Consistency 2. Performance Optimization 3. Compatibility Issues 20 10 10/30/2024 Strategies for Handling Fragmentation 1. Responsive and Adaptive Design Techniques: Responsive Design: Use flexible grids, layouts, and media queries to ensure the UI automatically adjusts to fit any screen size. Adaptive Design: Build multiple versions of the UI for specific screen sizes or breakpoints (e.g., small, medium, large) to provide an optimized experience. 21 Strategies for Handling Fragmentation 2. Dynamic Asset Management: Use scalable vector graphics (SVG) and multiple-resolution image assets to ensure images display correctly on all screen densities. Employ density-independent pixels (dp) in Android and points (pt) in iOS to scale UI elements proportionally across different devices. 22 11 10/30/2024 Strategies for Handling Fragmentation 3. Testing Across Devices and Emulators: Real Device Testing: Use actual devices for critical testing to observe real-world performance, touch responses, and app behavior. Emulators and Cloud Testing Platforms: Utilize tools like BrowserStack or Firebase Test Lab to simulate app behavior on various devices and OS versions without owning each device. 23 Strategies for Handling Fragmentation 4. Backward Compatibility: Ensure that the app supports older OS versions while still taking advantage of the latest features on newer versions. Use feature detection techniques to enable or disable functionalities based on the device's capabilities. 24 12 10/30/2024 Case Study on Device Fragmentation Cross-Device Consistency: Both apps deliver a similar user experience across various devices by maintaining a uniform UI. Responsive Design: Use of flexible layouts that adapt to different screen sizes and resolutions. Dynamic Scaling: UI elements scale based on screen density to remain crisp and touch-friendly. Backward Compatibility: Support for older OS versions to ensure functionality on various devices. Platform-Specific Guidelines: For a native look and feel, follow Material Design (Android) and Human Interface Guidelines (iOS). Feature Detection: Adapt app functionalities based on device capabilities to optimize performance. 25 Good Practices Consistency: Ensure a familiar interface on all devices. Adaptability: Design responsive and scalable UI elements. Testing: Use tools to identify and fix fragmentation-related issues. Platform Guidelines: Align designs with Android and iOS standards for a native experience. 26 13 10/30/2024 Create First App 27 Creating your first mobile application Understanding the File Structure: MainActivity.java: The main Java file where we will write the logic for the app. activity_main.xml: The layout file defines the app’s user interface (UI). AndroidManifest.xml: Describes essential information about the app, such as its package name and activities. 28 14 10/30/2024 Edit the Layout (activity_main.xml) 29 Edit the Layout (activity_main.xml) 30 15 10/30/2024 Edit MainActivity.java package com.example.helloworldapp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } 31 16 10/30/2024 Mobile App Architecture 1 What is Mobile App Architecture? Structure of an app’s core elements (data, presentation, navigation). 2 1 10/30/2024 Why Mobile App Architecture? Affects app performance, maintainability, and scalability. Differences by Platform: Android: MVVM or Clean Architecture. iOS: MVC or MVVM. 3 Android Activity Lifecycle Manages user interactions and resource handling. Example: Pausing an activity when a call interrupts. 4 2 10/30/2024 Android Activity Lifecycle Lifecycle Stages: onCreate, onStart, onResume, onPause, onStop, onDestroy. 5 Lifecycle Stages and Methods: onCreate(Bundle savedInstanceState) Called when an Activity is first created. Initialization of the Activity, setting up UI, binding data, and initializing components. 6 3 10/30/2024 Lifecycle Stages and Methods: onStart(): Called after onCreate and made the Activity visible to the user but not yet in the front. Set up things that should be re-initiated every time the Activity becomes visible, such as registering receivers or starting animations. 7 Lifecycle Stages and Methods: onResume() Called when the Activity gains focus and becomes interactive. Start updates that need to occur every time the Activity is active, like starting animations, refreshing UI, or updating data. 8 4 10/30/2024 Lifecycle Stages and Methods: onPause() Called when the Activity is partially block, such as when a dialog appears or the user navigates away. Pause updates, animations, or audio playback, save data and commit changes. 9 Lifecycle Stages and Methods: onStop() Called when the Activity is no longer visible, often when the user opens a new Activity. 10 5 10/30/2024 Lifecycle Stages and Methods: onRestart() Called if an Activity is stopped and then restarted, such as when a user returns to the Activity from the Recent Apps menu. Use this to re-initialize any resources released in onStop. 11 Lifecycle Stages and Methods: onDestroy() Final method called before the Activity is destroyed, either due to user or system-initiated actions. Clean up any remaining resources, end background tasks, and perform any final state persistence if it has not already been handled. 12 6 10/30/2024 onCreate() protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d("Lifecycle", "MainActivity: onCreate called"); } 13 onStart() protected void onStart() { super.onStart(); Log.d("Lifecycle", "MainActivity: onStart called"); } 14 7 10/30/2024 onResume() protected void onResume() { super.onResume(); Log.d("Lifecycle", "MainActivity: onResume called"); } 15 onPause() protected void onPause() { super.onPause(); Log.d("Lifecycle", "MainActivity: onPause called"); } 16 8 10/30/2024 onStop() protected void onStop() { super.onStop(); Log.d("Lifecycle", "MainActivity: onStop called"); } 17 onDestory() protected void onDestroy() { super.onDestroy(); Log.d("Lifecycle", "MainActivity: onDestroy called"); } 18 9 10/30/2024 Components of Android Apps - Activities An Activity in Android is a single screen with a user interface, like a web page on a website. Example: News feed, Editing a document, Navigating a map 19 Components of Android Apps - Activities An Activity in Android is a single screen with a user interface, like a web page on a website. Example: Home Activity: Shows a list of news articles. Detail Activity: Shows the full content of a selected article. Settings Activity: Allows the user to configure app settings. 20 10 10/30/2024 Purpose of Activities Display a user interface for user interaction. Handle user input and respond to touch, keyboard, or system events. Manage transitions between different screens in an app Act as an entry point into an app. When you launch an app, you start at its main Activity. 21 Activity Lifecycle onCreate(): Called when the Activity is first created. onStart(): The Activity becomes visible to the user but is not yet in the foreground. onResume(): The Activity becomes interactive in the foreground. onPause(): The Activity is about to lose focus, so it’s partially visible but not fully interactive. onStop(): The Activity is no longer visible when another Activity takes over the screen. onDestroy(): Called before the Activity is completely removed from memory. 22 11 10/30/2024 Components of Android Apps - Fragments A Fragment represents a reusable portion of an app's user interface within an Activity. Fragments are designed to be embedded within an Activity and occupy part or all of an Activity’s screen. Fragments allow us to create a modular UI design that can be reused across screens or app sections. For example: In a news app: You might have a Fragment for displaying a list of articles and another for showing the content of a selected article. In a settings screen: Each Fragment might represent a separate settings category, like account preferences or notification settings. 23 Purpose of Fragments Reusability Dynamic UI Design Simplified Navigation Lifecycle Awareness 24 12 10/30/2024 Components of Android Apps - Intents An Intent is an abstract description of an operation to be performed. Intents enable Android apps to do a wide variety of tasks, such as: Starting a new activity (screen) within the same or another application. Starting a service to perform background operations. Broadcasting a message to other apps. Receiving data or passing data between different components. 25 Types of Intents Explicit Intent Implicit Intent 26 13 10/30/2024 Explicit Intent An Explicit Intent is used to launch a specific component (like an Activity or Service) within the same application. Example: Intent intent = new Intent(this, SecondActivity.class); startActivity(intent); 27 Implicit Intent An Implicit Intent does not specify a specific component. Implicit Intents allow communication between different applications. Example: Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.example.com")); startActivity(intent); 28 14 10/30/2024 Passing Data with Intent Extras Intent intent = new Intent(this, SecondActivity.class); intent.putExtra("username", "JohnDoe"); startActivity(intent); Second Activity: String username = getIntent().getStringExtra("username"); 29 Implementing Activities and Fragments in Android public class MainActivity extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ListFragment()).commit(); } 30 15 10/30/2024 Implementing Activities and Fragments in Android public class ListFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_list, container, false); Button detailsButton = view.findViewById(R.id.details_button); detailsButton.setOnClickListener(v -> { getParentFragmentManager().beginTransaction().replace(R.id.fragment_container, new DetailFragment()).addToBackStack(null).commit(); }); 31 Implementing Activities and Fragments in Android 32 16 11/3/2024 User Interface Layout 1 User interface Terminologies Orientation: The screen’s orientation from the user's point of view. There are two screen orientations: Landscape orientation has a widescreen aspect ratio while Portrait orientation has a tall screen aspect ratio. Different devices operate in different orientations by default, which can change at runtime when the user rotates the device. 2 1 11/3/2024 User interface Terminologies Resolution: The total number of physical pixels on a screen. Screen size is the Actual physical size, measured as the screen's diagonal. For simplicity, Android categorizes all actual screen sizes into four generalized sizes: small, normal, large, and extra large. 3 User interface Terminologies Screen density is the quantity of pixels within a physical area of the screen, usually referred to as dpi (dots per inch). Android categorizes screen densities as low, medium, high, and extra high. A "low" density screen has fewer pixels within a given physical area compared to a "normal" or "high" density screen. 4 2 11/3/2024 User interface Terminologies Illustration of how Android roughly maps actual screen sizes and screen densities to generalized sizes and densities (figures are not exact). 5 User interface Terminologies Density-independent pixel (dp): A virtual pixel unit that should be used when defining UI layout, to express layout dimensions or position in a density-independent way. The dp is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. 6 3 11/3/2024 User interface Terminologies Android categorizes all density-independent pixel (dp) sizes into four generalized sizes: small, normal, large, and extra large. xlarge screens are at least 960dp x 720dp large screens are at least 640dp x 480dp normal screens are at least 470dp x 320dp small screens are at least 426dp x 320dp 7 User interface Terminologies The formula for converting dp units to screen pixels is as follows: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. dp units are used when defining the application’s UI to ensure proper UI display on screens with different densities. 8 4 11/3/2024 Units for specifying user interface The following table shows a list of units that are used to specify dimensions of user interface 9 User Interface Layout The user interface layout of the Android application is defined using a hierarchy of Views and ViewGroups In a single Android user interface, Views and View groups are organized into a hierarchical tree structure. View groups are placed at the root and intermediate positions of the tree, while Views are placed at the tree’s leaf nodes. A single-user interface can only have one root element 10 5 11/3/2024 Views A View is a basic building block of UI (User Interface) in Android. A view is a small rectangular box that responds to user inputs. Eg: EditText, Button, CheckBox, etc. View refers to the android.view.View class is the base class of all UI classes. View is responsible for event handling and drawing. 11 ViewGroup So what about a ViewGroup? A ViewGroup is a subclass of the View class. ViewGroup acts as a base class for layouts and layout parameters. The ViewGroup provides an invisible container to hold other Views or ViewGroups and to define the layout properties. For example, Linear Layout is the ViewGroup that contains UI controls like Button, TextView, date picker etc., and other layouts also. ViewGroup Refer to the android.view.ViewGroup class is the base class of some special UI classes that can contain other View objects as children. Since ViewGroup objects are also View objects, multiple ViewGroup objects and View objects can be organized into an object tree to build a complex UI structure. 12 6 11/3/2024 View Group Examples Examples of the commonly used ViewGroup subclasses used in Android applications are; ❖ FrameLayout ❖ WebView ❖ ListView ❖ GridView ❖ LinearLayout ❖ RelativeLayout ❖ TableLayout The above are generally termed layouts. This will form our next item of discussion. But then, before discussing layouts, what is the difference between a view and a viewgroup? 13 Differences between a view and a ViewGroup; 14 7 11/3/2024 Android Layouts 15 Android Layout Android Layout defines the user interface, which holds the UI controls or widgets that will appear on an Android application or activity screen. Generally, every application is a combination of View and ViewGroup. All the elements in a layout are built using a hierarchy of View and ViewGroup objects. A View usually draws something the user can see and interact with. Whereas a ViewGroup is an invisible container that defines the layout structure for View and other ViewGroup objects. 16 8 11/3/2024 Illustration of a view hierarchy, which defines a UI layout 17 Android Layout The View objects are usually called "widgets" and can be one of many subclasses, such as Button or TextView. The ViewGroup objects are usually called "layouts“. The ViewGroup can be one of many types that provide a different layout structure, such as LinearLayout or ConstraintLayout. 18 9 11/3/2024 How to declare a layout? You can declare a layout in several ways: You can declare UI elements in XML. Android provides a straightforward XML vocabulary corresponding to View classes and subclasses, such as those for widgets and layouts. Declaring your UI in XML allows you to separate your app’s presentation from the code that controls its behavior. Using XML files also makes it easy to provide different layouts for different screen sizes and orientations. 19 Android Layout The Android framework allows you to use either or both methods to build your app's UI. For example, you can declare your app's default layouts in XML and modify the layout at runtime. 20 10 11/3/2024 Android Layout Use Android Studio's Layout Editor to build your XML layout using a drag-and-drop interface. The Layout Editor lets you quickly build layouts by dragging UI elements into a visual design editor instead of writing layout XML by hand. The design editor can preview your layout on different Android devices and versions, and you can dynamically resize it to ensure it works well on various screen sizes. Initiate layout elements at runtime. App can programmatically create View and ViewGroup objects (and manipulate their properties). 21 Android Layout Layout resources are stored as XML files in the /res/layout resource directory for the application. 22 11 11/3/2024 Examples of layout The most common layouts provided by Android are : 1. LinearLayout: 2. FrameLayout 3. RelativeLayout 4. TableLayout: 5. Tab layout 6. Constraint Layout 23 LinearLayout: Linear layout arranges controls (its children) in a single column or row. Controls can be aligned in one of the following directions. 1. Horizontally, this will only be one row high (the height of the tallest child, plus padding). 2. Vertically, this will only have one child per row, no matter how wide they are Linear layout is the most common layout 24 12 11/3/2024 1. Linear Layout:XML File Example: The following XML code shows a linear layout as the root view group with a text view and a button 25 1. Linear Layout: XML File XML code in this example can be explained as follows: Specify the XML version number(1.0) and used for character encoding standard (utf 8) used in the document. UTF-8 stands for Universal Character Set Transformation Format, which uses 1 byte (8 bits) to represent characters in the ASCII set and two or three bytes for the rest. 26 13 11/3/2024 1. Linear Layout: XML File defines the beginning of the linear layout file defines the end of the linear layout file xmlns:android=http://schemas.android.com/apk/res/android The file declares Java package for the application attribute Known as android, which is considered the root of the application. 27 1. Linear Layout: XML File android:layout_width="fill_parent“ Assign layout width equal to the width of the screen Assign layout height with the height of the screen android:layout_height=“fill_parent. “ This means that the layout’s height and width will be proportional to the screen. Match_ parent value can also be used instead of fill_parent in API. Example : android:layout_width="match_parent“ android:layout_height="match_parent“ 28 14 11/3/2024 1. Linear Layout: XML File android:orientation="vertical“ Declares the orientation attribute and initializes it with a value for the vertical direction This means that all children will be aligned vertically All children are stacked one after the other such that a vertical list will only have one child per row, no matter how wide they are Example 29 2. RelativeLayout Arrange view objects (its children) in relation to each other or the parent. For Example, If the first control is centered on the screen, other controls Will be aligned relative to the screen center Relative layout is often used to create forms. 30 15 11/3/2024 2. RelativeLayout Example Example output 31 2. RelativeLayout Example Example: XML file with Relative layout 32 16 11/3/2024 2. RelativeLayout Example Element in this example can be explained as follows: android:layout_height="wrap_content“ android:layout_width ="wrap_content“ Sets the height of a container (i.e., group view) to the height of its contents (children). This means that its height and width will expand only far enough to contain its contents, such as text or other child controls it. 33 2. RelativeLayout Example The children of the layout are identified by their unique identity values. For example: Button android:id= "@+id/ok“ Button android:id= "@+id/cncle“ In this example, "@+id/ok“ and "@+id/cncle“ values identify individual command buttons in the layout. The plus-symbol (+) means that this is a new resource name that must be created and added to application resources (in the R.java file). 34 17 11/3/2024 2. RelativeLayout Example android:layout_alignParentRight ="true“ Aligns the control to the right of the parent (e.g., layout) android:layout_toLeftOf="@id/ok“ Aligns a control to the left of another control with A unique identity /ok (in this case, ok button) android:layout_marginLeft ="10dp“ Aligns the control to 10 Density-independent pixels (dp) from the Left margin: 35 2. RelativeLayout Example Example output 36 18 11/3/2024 3. TableLayout: Table layout arranges controls (its children) in rows and columns, like an HTML table Each row has zero or more cells defined by any other View. So, the cells of a row may be composed of various View objects, like ImageView or TextView objects. 37 3. TableLayout: XML Example 38 19 11/3/2024 3. TableLayout: XML Example element defines the beginning of a table layout element defines the end of a table layout element specifies the beginning of a table row element defines the end of a table row 39 3. TableLayout: XML Example android:padding="3dip” Sets the space size between the view border and its contents. In TextView, padding is shifting a text inside it, but in Layout View, padding is shifting all layout elements. 40 20 11/3/2024 3. TableLayout: XML Example android:gravity=“ " positions the contents of that view (i.e., what’s inside the view) on the right side android:layout_gravity can position the view for its parent (i.e., what the view is contained in). E.g android:layout_gravity="right“ This statement positions the view on the right side of the layout 41 4. FrameLayout: FrameLayout creates a blank space on the screen that can be filled with a single object For example, a picture that you'll swap in and out. All its children(controls) start at the top left of the screen. you cannot specify a different location for a child view. Subsequent child views will simply be drawn over previous ones, partially or totally Observing them (unless the newer object is transparent). 42 21 11/3/2024 4. FrameLayout: Generally, FrameLayout should be used to hold a single child view because it can be difficult to organize child views in a scalable way to different screen sizes without the children overlapping each other. The FrameLayout is mainly used for tabbed views and image switchers. 43 4. FrameLayout: Example This XML example , the image is displayed on the center of Text view but at the left side of the frame layout 44 22 11/3/2024 4. FrameLayout: Example 45 4. FrameLayout: Example XML code in this example can be explained as follows: android:layout_width="fill_parent“ android:layout_height="fill_parent“ Sets layout height and width to the height of the screen android:src="@drawable/ic_launcher" Assigns "@drawable/ic_launcher“ image to src attribute 46 23 11/3/2024 4. FrameLayout: Example android:text="Frame Demo“ Assigns “Frame Demo“ value to Text attribute android:scaleType="fitCenter“ Adjust the object to fit at the center of its container proportionally. In this example, the object is “ ic_launcher” image and the container is element 47 4. FrameLayout: Example android:layout_height="250px" android:layout_width="250px“ Defines the height and the width of the view.(e.g Image View ) android:gravity="center“ Positions contents of the view on the center. In this example, the image is positioned at the center of Text view 48 24 11/3/2024 4. FrameLayout: Example This XML example , the image is displayed on the center of Text view but at the left side of the frame layout 49 5. Tab Layout A tab Layout has 2 main elements 1. Tab indicator e.g, Label or Label and Icon 2. Content: Tab content e.g. View or Activity 50 25 11/3/2024 6. Constraint Layout Constraint Layout is a ViewGroup (i.e. , a view that holds other views) that allows you to create large and complex layouts with a flat view hierarchy and allows you to position and size widgets in a very flexible way. It was created to help reduce the nesting of views and improve layout file performance. Constraint Layout is very similar to RelativeLayout in such a way because, views are laid out according to relationships between sibling views and the parent layout yet it’s a lot more flexible and works better with the Layout Editor of the Android Studio’s. 51 6. Constraint Layout – diagram: 52 26 11/3/2024 Constraint Layout Advantages Of Constraint Layout Over Other Layouts One great advantage of the constraintlayout is that you can perform animations on your Constraint Layout views with very little code. You can build your complete layout with simple drag-and-drop on the Android Studio design editor. You can control what happens to a group of widgets through a single line of code. Constraint Layout improves performance over other layout 53 Loading Layout XML Resource Android compiles the XML layout code that is later loaded in java code by the following method: Public void oncreate (Bundle savedinstancesstate) { ….. Setcontentview(R.layout.); …} 54 27 11/3/2024 Loading Layout XML Resource A layout file is referenced using the following syntax: R.layout. for instance, this example loads activity_main.xml file in the onCreate() method 55 Terminologies of Views and view groups Padding is the space inside the border, between the border and the actual view's content. Margins are the spaces outside the border, between the border and the other elements next to the view. Example: 56 28 11/3/2024 Operations on views Common operations that can be performed on Views are: 1. Set properties by putting values of attributes in the XML layout files. E.g. Layout_width=“fill parent”, Layout_height=“wrap content” 2. Set focus on view in response to user input by using the requestFocus() method. 3. Set up listeners by putting listeners that will be notified when something interesting happens to the view control. For example, a Button notifies a listener to call clients when the button is clicked. 3. Set visibility by hiding or showing views using setVisibility(int) method 57 29 11/16/2024 Display Lists of data 1 Display lists of data In Android there are three main way to display data for the user to interact with A Drop-Down List box, which android calls a spinner widget. ListView Used mostly to display data in a simple format, but it be can be very complex. RecyclerView The successor to a ListView, can be very simple or complex in the way it displays data These each take a "list" of data and use an adapter to display the data to the user. 2 1 11/16/2024 Spinner Uses a spinner widget in the XML An array of data is provided Uses likely a built in Android adapter to display the data ArrayAdapter uses a simple layout, which can be one of the android.R.layout.X http://developer.android.com/intl/zh- CN/reference/android/R.layout.html for the full list We can get very fancy, like listview. 3 Spinner A spinner needs "items" to fill the drop-down box. This is done using an ArrayAdapter Using a string[] items, we can ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, items); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Then use setAdapter(adapter); //fills the list Add listener, setOnItemSelectedListener(this) implement AdapterView.OnItemSelectedListener public void onItemSelected(AdapterView parent, View view, int position, long id) Where position is the position in the array for the item selected. 4 2 11/16/2024 Listview The spinner shown before is a very similar to a list view A listView can be the only widget on the screen (no layout is needed) and can get very complex with the adapter. The items in the list are normally clickable. 5 Listview A listView can just be another widget in the layout as well. 6 3 11/16/2024 Listview Or a very complex, which multiple widgets in each item in the list Also true for the spinner 7 Listview and listFragment There is a listfragment that can be used (also a listactivity too). It has a default layout which contains a listview. You use the setListAdapter(adapter) method And you override the OnListItemClick Or you can just use a fragment, create the layout with a listview (and other views/widgets) And provide you own code to run the listview. 8 4 11/16/2024 Listview and listFragment public class Simple extends ListFragment { @Override The layout is how the items public void onActivityCreated(Bundle savedInstanceState) { will be displayed super.onActivityCreated(savedInstanceState); // NOTE, there is no xml layout for this activity! String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" }; ArrayAdapter adapter = new ArrayAdapter(requireActivity(),android.R.layout.simple_list_item_1, values); setListAdapter(adapter); } //This responses to the click event. @Override protected void onListItemClick(ListView l, View v, int position, long id) { String item = (String) getListAdapter().getItem(position); Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show(); } } 9 Changing the layout ArrayAdapter adapter = new ArrayAdapter(requireActivity() , R.layout.rowlayout, R.id.label, values); setListAdapter(adapter); Uses a layout we created and the label is where the item is go. In this case with an picture. 10 5 11/16/2024 rowlayout.xml Using our custom layout, the listView displays an picture (the same picture for all items) And we need a textview to display the “item” for each one. Which is called label in this case (you can choose whatever name). 11 More complex ListViews. If you want to display more then one piece of information per item, then you can have not only change the layout, but extend the ArrayAdapter or BaseAdapter. 12 6 11/16/2024 ArrayAdapter The ArrayAdapter already extends the BaseAdapter and provides a lot of built in methods. In the ListFragment (or Fragment) you would do something like this: ArrayAdapter adapter = new InteractiveArrayAdapter(this, myModelList); setListAdapter(adapter); Where myModleList is a list Where model is a class you created. 13 ArrayAdapter (2) public class InterActive_myArrayAdapter extends ArrayAdapter { private final List list; private final Activity context; InteractiveRowlayoutBinding binding; public InterActive_myArrayAdapter(Activity context, List list) { super(context, R.layout.interactive_rowlayout, list); this.context = context; this.list = list; } @Override public View getView(int position, View convertView, ViewGroup parent) { //this will look very similar to onCreate or OnCreateView, using binding. } } 14 7 11/16/2024 getView So for this one, we have TextView and checkBox. The List tells us if it’s checked or not. In getView, we create the View 15 getView if (convertView == null) { binding = InteractiveRowlayoutBinding.inflate(context.getLayoutInflater()); } else { binding = InteractiveRowlayoutBinding.bind(convertView); } binding.label.setText(list.get(position).getName()); binding.check.setChecked(list.get(position).isSelected()); binding.check.setOnCheckedChangeListener(new OnCheckedChangeListener() { … see the code. }); //Tag is an like a temp space, in a widget where you can set some information as an Object Class //in this case, the position variable. binding.check.setTag(String.valueOf(position)); //used to find the list position when we change the check mark onBind = false; //end of setting data. return binding.getRoot(); 16 8 11/16/2024 Custom ListViews We want to very complex and provide our own interface, then normally we extend the baseAdapter to create “fragments” for each item in the ListView. In this case a Phone class is created to hold all the Information, which passed to an extended baseAdapter. 17 RecyclerView a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Provides built Layout manages for positions default animations for common item operations, such as removal or addition of items https://developer.android.com/training/material/lists-cards.html 18 9 11/16/2024 RecyclerView (2) Like the listview, uses an adapter We normally use a cardview as the default layout for each item in the list. Similar to a fragment. 19 CardView extends the FrameLayout class and lets you show information inside cards that have a consistent look across the platform. CardView widgets can have shadows and rounded corners. Android 5.0+ (API 21+) use card_view:cardElevation attribute. CardView is not required with the recyclerView. They are just commonly used together. 20 10 11/16/2024 Including You need to include the them in the dependencies (build.gradle module) implementation 'androidx.recyclerview:recyclerview:1.3.2' implementation 'androidx.cardview:cardview:1.0.0' versions as of Aug 23, 2024 21 RecyclerView Add the following to your layout In your activity use the following code, (very similar to a listview) binding.list.setLayoutManager(new LinearLayoutManager(this)); binding.list.setItemAnimator(new DefaultItemAnimator()); setup the adapter, which is myAdapter, see the next slide for code. There is no simple adapter version, you need to extend it. mAdapter = new myAdapter(values, R.layout.my_row, this); binding.list.setAdapter(mAdapter); 22 11 11/16/2024 Recyclerview.Adapter public class myAdapter extends RecyclerView.Adapter { private List myList; private int rowLayout; private Context mContext; //constructor public myAdapter(List myList, int rowLayout, Context context) { this.myList = myList; this.rowLayout = rowLayout; this.mContext = context; } // Create new views (invoked by the layout manager) @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { MyRowBinding v = MyRowBinding.inflate(LayoutInflater.from(mContext), viewGroup, false); return new ViewHolder(v); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return myList == null ? 0 : myList.size(); } 23 Recyclerview.Adapter (2) //viewbinding provides the references now. public static class ViewHolder extends RecyclerView.ViewHolder { public MyRowBinding viewBinding; public ViewHolder(MyRowBinding viewBinding) { super(viewBinding.getRoot()); this.viewBinding = viewBinding; } } 24 12 11/16/2024 My_row.xml and cardView 29 Swipe Down/refresh (2) Java code, then setups a listener for it. And optionally set colors for the refresh loop. setup some colors for the refresh circle. Optional. binding.mSwipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue); now setup the swiperefrestlayout listener where the main work is done. binding.mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { Do/Call refresh code here } }); When the refresh is done, make this call to turn off the refresh UI. binding.mSwipeRefreshLayout.setRefreshing(false); 30 15 11/16/2024 Swipe left/right code. No changes to the xml are necessary. Uses the ItemTouchHelper callbacks First setup a simplecallback (next slide) Then attach the recyclerview to it. ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); itemTouchHelper.attachToRecyclerView(binding.mRecyclerView); 31 ItemTouchHelper.SimpleCallback Create the callback ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) { For both Left and right use: ItemTouchHelper.RIGHT |ItemTouchHelper.LEFT @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { //likely allows to for animations? or moving items in the view I think. return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { if (direction == ItemTouchHelper.RIGHT) { //Now remove the item from the list (likely in the adapter) int item = viewHolder.getAdapterPosition(); //Which item it is in the list. // don’t forget notifyDataSetChanged(); in the adapter as well. //you can combine this with a snackbar as simple, Do you really want to delete this. } } }; 32 16 11/24/2024 Display Lists of data 1 Display lists of data In Android there are three main way to display data for the user to interact with A Drop-Down List box, which android calls a spinner widget. ListView Used mostly to display data in a simple format, but it be can be very complex. RecyclerView The successor to a ListView, can be very simple or complex in the way it displays data These each take a "list" of data and use an adapter to display the data to the user. 2 1 11/24/2024 Spinner Uses a spinner widget in the XML An array of data is provided Uses likely a built in Android adapter to display the data ArrayAdapter uses a simple layout, which can be one of the android.R.layout.X Listeners like setOnItemSelectedListener handle selection events. 3 Define the Spinner in XML: 4 2 11/24/2024 Prepare Data: String[] items = {"Item 1", "Item 2", "Item 3"}; 5 Create and Set an Adapter: String[] items = {"Item 1", "Item 2", "Item 3"}; Spinner spinner = findViewById(R.id.spinner); 6 3 11/24/2024 Create and Set an Adapter: String[] items = {"Item 1", "Item 2", "Item 3"}; Spinner spinner = findViewById(R.id.spinner); ArrayAdapter adapter = new ArrayAdapter( this, android.R.layout.simple_spinner_item, items ); 7 Create and Set an Adapter: String[] items = {"Item 1", "Item 2", "Item 3"}; Spinner spinner = findViewById(R.id.spinner); ArrayAdapter adapter = new ArrayAdapter( this, android.R.layout.simple_spinner_item, items ); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdow n_item); 8 4 11/24/2024 Create and Set an Adapter: String[] items = {"Item 1", "Item 2", "Item 3"}; Spinner spinner = findViewById(R.id.spinner); ArrayAdapter adapter = new ArrayAdapter( this, android.R.layout.simple_spinner_item, items ); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); 9 This code creates a functional Spinner: 1.Retrieves the Spinner view from the XML layout. 2.Prepares an adapter to link the data (items) to the Spinner. 3.Specifies a layout for the dropdown menu items. 4.Binds the adapter to the Spinner so it can display the data. 10 5 11/24/2024 Handle Selection Events: spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 11 Handle Selection Events: spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { 12 6 11/24/2024 Handle Selection Events: spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { String selectedItem = items[position]; 13 Handle Selection Events: spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { String selectedItem = items[position]; Toast.makeText(getApplicationContext(), "Selected: " + selectedItem, Toast.LENGTH_SHORT).show(); 14 7 11/24/2024 Listview The spinner shown before is a very similar to a list view A listView can be the only widget on the screen (no layout is needed) and can get very complex with the adapter. The items in the list are normally clickable. 15 Listview A listView can just be another widget in the layout as well. 16 8 11/24/2024 Listview Or a very complex, which multiple widgets in each item in the list Also true for the spinner 17 Define the ListView in XML: 18 9 11/24/2024 Prepare Data: String[] items = {"Android", "iOS", "Windows"}; 19 Create and Set an Adapter: String[] items = {"Android", "iOS", "Windows"}; ListView listView = findViewById(R.id.list_view); 20 10 11/24/2024 Create and Set an Adapter: String[] items = {"Android", "iOS", "Windows"}; ListView listView = findViewById(R.id.list_view); ArrayAdapter adapter = new ArrayAdapter( this, android.R.layout.simple_list_item_1, items ); 21 Create and Set an Adapter: String[] items = {"Android", "iOS", "Windows"}; ListView listView = findViewById(R.id.list_view); ArrayAdapter adapter = new ArrayAdapter( this, android.R.layout.simple_list_item_1, items); listView.setAdapter(adapter); 22 11 11/24/2024 Handle Item Clicks: listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 23 Handle Item Clicks: listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { 24 12 11/24/2024 Handle Item Clicks: listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { String selectedItem = items[position]; 25 Handle Item Clicks: listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { String selectedItem = items[position]; Toast.makeText(getApplicationContext(), "Clicked: " + selectedItem, Toast.LENGTH_SHORT).show(); }); 26 13 11/24/2024 How It Works Together: 1.Register Listener 2.Handle Click 3.Fetch Data 4.Show Feedback 27 RecyclerView a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Provides built Layout manages for positions default animations for common item operations, such as removal or addition of items 28 14 11/24/2024 RecyclerView (2) Like the listview, uses an adapter We normally use a cardview as the default layout for each item in the list. Similar to a fragment. 29 CardView extends the FrameLayout class and lets you show information inside cards that have a consistent look across the platform. CardView widgets can have shadows and rounded corners. Android 5.0+ (API 21+) use card_view:cardElevation attribute. CardView is not required with the recyclerView. They are just commonly used together. 30 15 11/24/2024 Including You need to include the them in the dependencies (build.gradle module) implementation 'androidx.recyclerview:recyclerview:1.3.2' implementation 'androidx.cardview:cardview:1.0.0' versions as of Aug 23, 2024 31 Add RecyclerView in XML: 32 16 11/24/2024 Prepare Data: List items = Arrays.asList("Item 1", "Item 2", "Item 3"); 33 Create a Layout Manager: List items = Arrays.asList("Item 1", "Item 2", "Item 3"); RecyclerView recyclerView = findViewById(R.id.recycler_view); 34 17 11/24/2024 Create a Layout Manager: List items = Arrays.asList("Item 1", "Item 2", "Item 3"); RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); 35 Define an Adapter: List items = Arrays.asList("Item 1", "Item 2", "Item 3"); RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); public class MyAdapter extends RecyclerView.Adapter { 36 18 11/24/2024 Define an Adapter: List items = Arrays.asList("Item 1", "Item 2", "Item 3"); RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); public class MyAdapter extends RecyclerView.Adapter { private List data; 37 Define an Adapter: List items = Arrays.asList("Item 1", "Item 2", "Item 3"); RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); public class MyAdapter extends RecyclerView.Adapter { private List data; public static class ViewHolder extends RecyclerView.ViewHolder { TextView textView; 38 19 11/24/2024 Define an Adapter: List items = Arrays.asList("Item 1", "Item 2", "Item 3"); RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); public class MyAdapter extends RecyclerView.Adapter { private List data; public static class ViewHolder extends RecyclerView.ViewHolder { TextView textView; public ViewHolder(View itemView) { super(itemView); textView = itemView.findViewById(R.id.text_view); } 39 Define an Adapter: List items = Arrays.asList("Item 1", "Item 2", "Item 3"); RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); public class MyAdapter extends RecyclerView.Adapter { private List data; public static class ViewHolder extends RecyclerView.ViewHolder { TextView textView; public ViewHolder(View itemView) { super(itemView); textView = itemView.findViewById(R.id.text_view); } 40 20 11/24/2024 Define an Adapter: List items = Arrays.asList("Item 1", "Item 2", "Item 3"); RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); public class MyAdapter extends RecyclerView.Adapter { private List data; public static class ViewHolder extends RecyclerView.ViewHolder { TextView textView; public ViewHolder(View itemView) { super(itemView); textView = itemView.findViewById(R.id.text_view); } public MyAdapter(List data) { this.data = data; } 41 Define an Adapter: @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false); return new ViewHolder(view); 42 21 11/24/2024 Define an Adapter: @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false); return new ViewHolder(view); public void onBindViewHolder(ViewHolder holder, int position) { holder.textView.setText(data.get(position)); } 43 Define an Adapter: @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false); return new ViewHolder(view); public void onBindVi

Use Quizgecko on...
Browser
Browser