<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Debasish Raut on Medium]]></title>
        <description><![CDATA[Stories by Debasish Raut on Medium]]></description>
        <link>https://medium.com/@debasishraut.dev?source=rss-5503dc1080a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IFo7nmAnU5jMfo5Ov8-C_w.jpeg</url>
            <title>Stories by Debasish Raut on Medium</title>
            <link>https://medium.com/@debasishraut.dev?source=rss-5503dc1080a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:15:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@debasishraut.dev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Setting-up Smoothing Filters for MediaPipe Pose Estimation Pipeline using Python: A Practical Guide]]></title>
            <link>https://medium.com/@debasishraut.dev/setting-up-smoothing-filters-for-mediapipe-pose-estimation-pipeline-a-practical-guide-fcc03f462196?source=rss-5503dc1080a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcc03f462196</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[mediapipe]]></category>
            <category><![CDATA[human-pose-estimation]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[pose-estimation]]></category>
            <dc:creator><![CDATA[Debasish Raut]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 07:33:08 GMT</pubDate>
            <atom:updated>2025-11-29T03:06:33.980Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hands-on guide for applying Simple Moving Average filter to MediaPipe Pose Estimation Pipeline and help set up the development environment to test and compare effectiveness of various types of filters.</h4><h3>Table of Contents</h3><ol><li>Introduction</li><li>Prerequisites</li><li>Version and Environment Details</li><li>MediaPipe Pipeline Setup</li><li>Class Design for Pose Estimation</li><li>Simple Moving Average Filter</li><li>What the future holds</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v22uaWOhN92RqYZV" /><figcaption>Photo by <a href="https://unsplash.com/@aoddeh?utm_source=medium&amp;utm_medium=referral">Ahmad Odeh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Accurately tracking human poses from video is a complex challenge, especially when body parts are obscured or move out of frame, causing jitter and unreliable data. This can be critical in applications ranging from sports analytics to AI surveillance. MediaPipe Pose Landmarker is a powerful tool for pose detection, but raw landmark data can be noisy. Applying smoothing filters like Kalman, Exponential Moving Average, and One-Euro helps reduce jitter and improve the stability of pose estimations.</p><h3>Prerequisites</h3><ul><li>Basic knowledge of Python programming.</li><li>Familiarity with computer vision concepts.</li><li>Working installation of Python (version 3.7 or above).</li><li>Experience with NumPy and OpenCV is beneficial.</li></ul><h4>Version and Environment Details</h4><p>This guide uses the latest MediaPipe Pose Landmarker models and APIs released in January 2025. Ensure you have:</p><ul><li>Python 3.7 or above</li><li>MediaPipe installed via python -m pip install mediapipe --upgrade</li><li>The appropriate pre-trained model from the <a href="https://ai.google.dev/edge/mediapipe/solutions/vision/pose_landmarker">Official Solutions Guide</a> (recommended: Full model for demonstration)</li></ul><h3>MediaPipe Pipeline Setup</h3><h4>Installation</h4><pre>$ python -m pip install mediapipe</pre><p>Download your preferred pose landmarker model from the official guide. For this demonstration, the full model is recommended. Also ensure you have OpenCV installed (pip install opencv-python).</p><h4>Why?</h4><ul><li>mediapipe: Core pose detection library.</li><li>opencv-python: Efficient video reading/writing and per-frame image manipulation.</li><li>numpy: Fast numerical array operations for frame/image and landmark buffer handling.</li></ul><h4>Why the ‘full’ model?</h4><p>The “Full” pose landmarker strikes a balance between accuracy and performance. The “Lite” version is fastest but can miss fine-grained landmarks in challenging scenarios; “Heavy” is most accurate but computationally expensive. For most prototyping and smoothing filter evaluation, “Full” is the optimal choice.</p><h4>Landmark Structure in MediaPipe</h4><p>Landmarks are represented as Protocol Buffers.</p><ul><li>Landmark: Holds x, y, z, visibility, presence.</li><li>NormalizedLandmarkList: List of normalized landmarks (each in range).</li></ul><p>These enable efficient serialization, manipulation, and extension for additional processing and filtering steps.</p><h4>Landmark Data Structure: Protobuf Definitions</h4><p>MediaPipe uses Protocol Buffers (protobuf) to define and serialize landmark data in a format that is lightweight and easily portable across languages and platforms.</p><blockquote>Protocol Buffers, often called Protobuf, provide a method for serializing structured data in a language-neutral, platform-neutral, and extensible format. In Python, Protobuf is used to define data structures, generate Python classes from these definitions, and then serialize and de-serialize data using these classes.</blockquote><p>You can see the protobuf definition here: <a href="https://github.com/google-ai-edge/mediapipe/blob/master/mediapipe/framework/formats/landmark.proto">mediapipe/mediapipe/framework/formats/landmark.proto</a></p><p>You can see something like:</p><pre>message Landmark {<br>  optional float x = 1;<br>  optional float y = 2;<br>  optional float z = 3;<br>  // Landmark visibility. Should stay unset if not supported.<br>  // Float score of whether landmark is visible or occluded by other objects.<br>  // Landmark considered as invisible also if it is not present on the screen<br>  // (out of scene bounds). Depending on the model, visibility value is either a<br>  // sigmoid or an argument of sigmoid.<br>  optional float visibility = 4;<br>  // Landmark presence. Should stay unset if not supported.<br>  // Float score of whether landmark is present on the scene (located within<br>  // scene bounds). Depending on the model, presence value is either a result of<br>  // sigmoid or an argument of sigmoid function to get landmark presence<br>  // probability.<br>  optional float presence = 5;<br>}<br>// Group of Landmark protos.<br>message LandmarkList {<br>  repeated Landmark landmark = 1;<br>}<br>// Group of LandmarkList protos.<br>message LandmarkListCollection {<br>  repeated LandmarkList landmark_list = 1;<br>}<br>// A normalized version of above Landmark proto. All coordinates should be<br>// within [0, 1].<br>message NormalizedLandmark {<br>  optional float x = 1;<br>  optional float y = 2;<br>  optional float z = 3;<br>  optional float visibility = 4;<br>  optional float presence = 5;<br>}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ce5d83a3c5859cc362bead9922fcc21/href">https://medium.com/media/0ce5d83a3c5859cc362bead9922fcc21/href</a></iframe><p>Visibility and presence scores allow you to down-weight, ignore, or treat noisy/occluded landmarks differently during smoothing. For example, a Kalman filter can set its gain lower or freeze movement for landmarks with low visibility.</p><p>When applying a smoothing filter, you copy the x, y, z, visibility, presence fields, apply your transform, and build a new NormalizedLandmarkList for downstream visualization or analysis.</p><h4>Transformation and Filtering of Landmarks</h4><p>Transformation functions are integrated into the PoseEstimator class. They operate on each landmark&#39;s x, y, z, visibility, presence and output modified landmark tuples that can be further processed or visualized.</p><p>Example placeholder transform:</p><pre>def transform_func(self, x, y, z, visibility, presence, idx):<br>    return x+0.1, y+0.1, z+0.1, visibility, presence</pre><p>Real filtering algorithms (like Kalman, EMA, etc.) will replace this function to reduce jitter and output more stable landmark trajectories.</p><p>We have the basic pose estimation setup. Now we want a way to visualize our results. We can get just that from the solutions module. We will write this function inside the class scope in the next section.</p><p>We can process each frame through this function and convert the video frames to new frames annotated with the pose landmarks data. This will help us visualize the difference between our original and the filtered outputs.</p><h3>Class Design for Pose Estimation</h3><p>Having a clean, modular pipeline is essential for reliable pose smoothing experiments. In this section, we’ll organize the PoseEstimator class so readers can both understand and reuse every component. We&#39;ll rely on a configuration file for paths and hyper-parameters (tips on this below), and each code snippet will be self-contained, type-annotated, well-commented, and use idiomatic Python throughout.</p><p>Code is organized into a PoseEstimator class responsible for initializing the model, processing video frames, extracting and transforming pose landmarks, and managing buffers. Key methods handle model setup, video reading, frame processing, and landmark transformation.</p><h4>1. Project-Wide Configuration</h4><p>All settings and file paths are managed in config.py for easy tuning and reproducibility.</p><p>config.py</p><pre>VIDEO_PATH = &quot;../Assets/explosive.mp4&quot;<br>VIDEO_OUT_PATH = &quot;../out/mp_annot.mp4&quot;<br>MODEL_PATH = &quot;../models/pose_landmarker_full.task&quot;</pre><h4>2. Imports and Class Definition</h4><pre>from config import MODEL_PATH, VIDEO_OUT_PATH, VIDEO_PATH, SMA_WINDOW<br><br>import cv2<br>import mediapipe as mp<br>import numpy as np<br>from collections import deque<br>from mediapipe.framework.formats import landmark_pb2<br>from mediapipe import solutions</pre><h4>3. PoseEstimator Initialization Block</h4><p>What it does: Instantiates model, initializes buffers, prepares lists for results.</p><pre>class PoseEstimator:<br>    &quot;&quot;&quot;<br>    A class to handle pose estimation from video files using MediaPipe.<br>    &quot;&quot;&quot;<br>    def __init__(self, model_path: str):<br>        &quot;&quot;&quot;<br>        Initialize the PoseEstimator with model path and smoothing window size.<br>        <br>        Args:<br>            model_path: Path to the MediaPipe pose landmarker model (.task file)<br>            sma_window: Simple Moving Average window size for landmark smoothing<br>        &quot;&quot;&quot;<br>        self.model_path = model_path<br>        self.pose_detector = self._init_pose_detector()<br>        self.landmarks_list = []</pre><h4>4. Model and Video IO Setup Methods</h4><pre>    def _init_pose_detector(self) -&gt; mp.tasks.vision.PoseLandmarker:<br>        &quot;&quot;&quot;<br>        Initialize MediaPipe PoseLandmarker with VIDEO running mode.<br>        <br>        Returns:<br>            PoseLandmarker: Configured pose detection model<br>        &quot;&quot;&quot;<br>        BaseOptions = mp.tasks.BaseOptions<br>        PoseLandmarker = mp.tasks.vision.PoseLandmarker<br>        PoseLandmarkerOptions = mp.tasks.vision.PoseLandmarkerOptions<br>        VisionRunningMode = mp.tasks.vision.RunningMode<br>        <br>        options = PoseLandmarkerOptions(<br>            base_options=BaseOptions(model_asset_path=self.model_path),<br>            running_mode=VisionRunningMode.VIDEO<br>        )<br>        return PoseLandmarker.create_from_options(options)<br>    <br>    def _init_video_capture(self, video_path: str) -&gt; tuple:<br>        &quot;&quot;&quot;<br>        Initialize video capture and extract video properties.<br>        <br>        Args:<br>            video_path: Path to the video file<br>            <br>        Returns:<br>            tuple: (VideoCapture object, fps, frame_width, frame_height)<br>        &quot;&quot;&quot;<br>        cap = cv2.VideoCapture(video_path)<br>        fps = cap.get(cv2.CAP_PROP_FPS)<br>        frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))<br>        frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))<br>        return cap, fps, frame_width, frame_height<br>    <br>    def _init_writer(self, out_path, fourcc, fps, dimensions):<br>        return cv2.VideoWriter(out_path, fourcc, fps, dimensions)</pre><h4>5. Frame Processing and Landmark Extraction</h4><p>Clear separation: Prepares and processes a single frame, making the main video loop readable and maintainable.</p><pre>def _process_frame(self, image: np.ndarray, timestamp_ms: int) -&gt; tuple:<br>        &quot;&quot;&quot;<br>        Process a single frame through the pose detector.<br>        <br>        Args:<br>            image: Frame in RGB format (numpy array)<br>            timestamp_ms: Timestamp in milliseconds for video frame<br>            <br>        Returns:<br>            tuple: (detection_result, mp.Image)<br>        &quot;&quot;&quot;<br>        mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=image)<br>        detection_result = self.pose_detector.detect_for_video(mp_image, timestamp_ms)<br>        return detection_result, mp_image</pre><h4>6. Landmark Transformation and Smoothing</h4><p>The transform_func is a placeholder where our filter functions will go. Currently, this is a simple transform function that does not do much other than add a small value to the incoming landmark values. The resultant output is a slightly shifted pose landmarks( you can test it out and play around with it).</p><p>The transform_landmarks function is used to process each landmark frame through our filter function one by one and storing them in one variable before returning the value to the concerned function.</p><pre>    def transform_func(self, x, y, z, visibility, presence, idx):<br>        return x+0.25, y, z, visibility, presence<br><br>    def _transform_landmarks(self, pose_landmarks_list: list, transform_func) -&gt; list:<br>        &quot;&quot;&quot;<br>        Applies transform_func to each landmark in each detected pose.<br><br>        Args:<br>            pose_landmarks_list: list of lists of landmarks (detection_result.pose_landmarks)<br>            transform_func: function that takes (x, y, z) and returns transformed (x, y, z)<br><br>        Returns:<br>            transformed_landmarks_list: list of lists of transformed landmarks as tuples (x, y, z)<br>        &quot;&quot;&quot;<br>        transformed_landmarks_list = []<br>        <br>        if not pose_landmarks_list:<br>            return transformed_landmarks_list<br>        <br>        for pose_landmarks in pose_landmarks_list:<br>            transformed_landmarks = []<br>            for i,landmark in enumerate(pose_landmarks):<br>                x, y, z, v, p = landmark.x, landmark.y, landmark.z, landmark.visibility, landmark.presence<br>                x_t, y_t, z_t, v_t, p_t = transform_func(x, y, z, v, p, idx=i)<br>                transformed_landmarks.append((x_t, y_t, z_t, v_t, p_t))<br>            <br>            transformed_landmarks_list.append(transformed_landmarks)<br>            self.landmarks_list.append(transformed_landmarks)<br>        <br>        return transformed_landmarks_list</pre><h4>7. Converting Processed Landmarks to MediaPipe’s NormalizedLandmarkList</h4><p>After applying smoothing or filtering algorithms to your pose landmarks, you’ll need to convert your processed results back into MediaPipe’s NormalizedLandmarkList protobuf format. This step ensures compatibility with downstream MediaPipe utilities—such as visualization, analytics, and exporting—by serializing your transformed data into the original data structure expected by the framework.</p><pre>def _create_landmark_proto(self, transformed_landmarks: list) -&gt; landmark_pb2.NormalizedLandmarkList:<br>        &quot;&quot;&quot;<br>        Convert transformed landmarks to MediaPipe protobuf format.<br>        <br>        Args:<br>            transformed_landmarks: List of transformed landmark tuples<br>            <br>        Returns:<br>            landmark_pb2.NormalizedLandmarkList: Protobuf representation of landmarks<br>        &quot;&quot;&quot;<br>        proto_landmarks = landmark_pb2.NormalizedLandmarkList()<br>        <br>        for pose_landmarks in transformed_landmarks:<br>            proto_landmarks.landmark.extend([<br>                landmark_pb2.NormalizedLandmark(<br>                    x=x, y=y, z=z, visibility=visibility, presence=presence<br>                ) for (x, y, z, visibility, presence) in pose_landmarks<br>            ])<br>        <br>        return proto_landmarks</pre><h4>8. Visualization / Annotation Utilities</h4><pre>def draw_landmarks_on_image(self, rgb_image, proto_landmarks):<br>        &quot;&quot;&quot;<br>        Draw pose landmarks on the image given protobuf NormalizedLandmarkList.<br><br>        Args:<br>            rgb_image: Input RGB image as a numpy array.<br>            proto_landmarks: A landmark_pb2.NormalizedLandmarkList object of pose landmarks.<br><br>        Returns:<br>            annotated_image: Image with landmarks drawn.<br>        &quot;&quot;&quot;<br>        annotated_image = np.copy(rgb_image)<br><br>        if proto_landmarks is None or len(proto_landmarks.landmark) == 0:<br>            return annotated_image<br><br>        solutions.drawing_utils.draw_landmarks(<br>            annotated_image,<br>            proto_landmarks,<br>            solutions.pose.POSE_CONNECTIONS,<br>            solutions.drawing_styles.get_default_pose_landmarks_style()<br>        )<br>        return annotated_image</pre><h4>8. Main Video Loop</h4><pre>    def process_video(self, video_path: str, out_path: str) -&gt; landmark_pb2.NormalizedLandmarkList:<br>        &quot;&quot;&quot;<br>        Process an entire video file and extract pose landmarks.<br>        <br>        Args:<br>            video_path: Path to the video file<br>            <br>        Returns:<br>            All extracted landmarks data of a single frame<br>        &quot;&quot;&quot;<br>        cap, fps, width, height = self._init_video_capture(video_path)<br>        fourcc = cv2.VideoWriter_fourcc(*&#39;mp4v&#39;)<br>        out = self._init_writer(out_path, fourcc, fps, (width, height))<br>        frame_count = 0<br>        try:<br>            while cap.isOpened():<br>                success, image = cap.read()<br>                if not success:<br>                    break<br>                # if(frame_count &gt; 20):<br>                #     break<br>                timestamp_ms = int(cap.get(cv2.CAP_PROP_POS_MSEC))<br>                image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br>                                <br>                detection_result, mp_image = self._process_frame(image_rgb, timestamp_ms)                <br>                <br>                if detection_result.pose_landmarks:<br>                    transformed_points = self._transform_landmarks(detection_result.pose_landmarks, self.transform_func )<br>                    proto_landmarks = self._create_landmark_proto(transformed_points)<br>                    annotated_image = self.draw_landmarks_on_image(mp_image.numpy_view(), proto_landmarks)<br>                    annotated_image_bgr = cv2.cvtColor(annotated_image, cv2.COLOR_RGB2BGR)<br>                    out.write(annotated_image_bgr)<br>                frame_count += 1<br>        finally:<br>            cap.release()<br>            out.release()<br>        return proto_landmarks<br>    <br>    </pre><h4>9. Accessing Processed Landmarks</h4><pre>def get_all_landmarks(self):<br>        return self.landmarks_list</pre><h4>Testing the base model without filtering</h4><pre>if __name__ == &quot;__main__&quot;:<br>    videoPath = &quot;../Assets/mediapipe_female.mp4&quot;<br>    modelPath = &quot;../models/pose_landmarker_full.task&quot;<br>    estimator = PoseEstimator(model_path=modelPath)<br>    <br>    pose_landmarks_list = estimator.process_video(video_path=videoPath)<br>   <br>    print(&quot;Pose estimation completed successfully!&quot;)<br>    print(f&quot;Extracted landmarks: {pose_landmarks_list}&quot;)</pre><p>Initialize the videoPath &amp; modelPath and run the main function of the class. If all the assets and models are in place you will get a output video which is MediaPipe PoseLandmark annotated with a slightly transformed values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*qNkHgRFT0_aDxuAKN3NNAA.gif" /><figcaption>Auditions for Natya@Berkeley. If we can make our models achieve accurate depiction on these dance movements, I think we should call it done.</figcaption></figure><h3>SIMPLE MOVING AVERAGE FILTER</h3><p>A <a href="https://www.investopedia.com/terms/s/sma.asp">simple moving average (SMA)</a> is calculated by taking the arithmetic mean of a given set of values over a specified period. This is as simple as it gets, we basically take the mean points in the neighborhood in order to smooth out the jitter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*ppxFl1x736cvfOka.png" /></figure><p>We should start with this function as an experiment, and we can gradually move to more complex filter functions and compare our results as we go.</p><p>Each pose from MediaPipe PoseEstimation consists of 33 landmarks. To apply SMA across a video, we maintain a buffer for each landmark, storing the last N sets of coordinates (where N = sma_window). Each buffer allows us to quickly compute the mean of each coordinate over the window.</p><pre>class PoseEstimator:<br>   . . . <br>        self.pose_detector = self._init_pose_detector()<br>        self.landmark_buffers = self._init_buffers()<br>        self.landmarks_list = []<br>   . . .</pre><p>These buffers will be updated very fast on each frame pose estimation cycle, so we need an apt data structure that is designed for fast appends and pop operations. That is why Python’s collections.deque (<a href="https://en.wikipedia.org/wiki/Double-ended_queue">Double Ended Queue</a>) is the best fit for it. By setting maxlen=sma_window, it automatically keeps only the N most recent items: when a new frame is added and the buffer is full, the oldest frame is dropped. Also appending and popping elements from a deque are O(1) operations (constant time), which is much faster than using a list.</p><p>So we write a new function within the class to initialize the buffers as collections.dequeue:</p><pre>def _init_buffers(self) -&gt; dict:<br>        &quot;&quot;&quot;<br>        Initialize deque buffers for each of the 33 pose landmarks.<br>        Each buffer stores the last `sma_window` frames of landmark coordinates.<br>        <br>        Returns:<br>            dict: Dictionary mapping landmark index to deque buffer<br>        &quot;&quot;&quot;<br>        return {i: deque(maxlen=self.sma_window) for i in range(33)}<br><br>def reset_buffers(self):<br>        &quot;&quot;&quot;Reset all landmark buffers. Call this before processing a new video.&quot;&quot;&quot;<br>        self.landmark_buffers = self._init_buffers()</pre><p>Next we add our transform function to calculate moving averages.</p><pre>def sma_transform_func(self, x, y, z, visibility, presence, landmark_buffers, idx):<br>        buffer = landmark_buffers[idx]<br>        buffer.append([x, y, z])<br>        if len(buffer) == buffer.maxlen:<br>            mean_x, mean_y, mean_z = np.mean(buffer, axis=0)<br>            return mean_x, mean_y, mean_z, visibility, presence<br>        else:<br>            return x, y, z, visibility, presence</pre><p>We simply find the mean of the pose landmark values(x,y, &amp; z co-ordinate) for the Pose Landmark node based on the number idx.</p><p>In our transform_landmarks function, we will modify it to include the transformation properly:</p><pre>def _transform_landmarks(self, pose_landmarks_list: list, transform_func, landmark_buffers) -&gt; list:<br>        &quot;&quot;&quot;<br>        Applies transform_func to each landmark in each detected pose.<br><br>        Args:<br>            pose_landmarks_list: list of lists of landmarks (detection_result.pose_landmarks)<br>            transform_func: function that takes (x, y, z) and returns transformed (x, y, z)<br><br>        Returns:<br>            transformed_landmarks_list: list of lists of transformed landmarks as tuples (x, y, z)<br>        &quot;&quot;&quot;<br>        transformed_landmarks_list = []<br>        <br>        if not pose_landmarks_list:<br>            return transformed_landmarks_list<br>        <br>        for pose_landmarks in pose_landmarks_list:<br>            transformed_landmarks = []<br>            for i,landmark in enumerate(pose_landmarks):<br>                x, y, z, v, p = landmark.x, landmark.y, landmark.z, landmark.visibility, landmark.presence<br>                x_t, y_t, z_t, v_t, p_t = sma_transform_func(x, y, z, v, p, landmark_buffers, idx=i)<br>                transformed_landmarks.append((x_t, y_t, z_t, v_t, p_t))<br>            <br>            transformed_landmarks_list.append(transformed_landmarks)<br>            self.landmarks_list.append(transformed_landmarks)<br>        <br>        return transformed_landmarks_list</pre><p>In process_video function, we include the new transform function instead of the old one. But we will also use the old shift transformation because it looked much more comprehensible that way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*zyaBPn-zVwp3vtraMQjUbA.gif" /><figcaption>Although the movements are much more smoother, they do not feel like natural movement. That is the limitation of simple filters like SMA.</figcaption></figure><p>Given below is the entire class definition with SMA filter applied with a X-Shift transformation applied to the resultant from SMA filter:</p><pre>class PoseEstimator:<br>    &quot;&quot;&quot;<br>    A class to handle pose estimation from video files using MediaPipe.<br>    &quot;&quot;&quot;<br>    def __init__(self, model_path: str):<br>        &quot;&quot;&quot;<br>        Initialize the PoseEstimator with model path and smoothing window size.<br>        <br>        Args:<br>            model_path: Path to the MediaPipe pose landmarker model (.task file)<br>            sma_window: Simple Moving Average window size for landmark smoothing<br>        &quot;&quot;&quot;<br>        self.model_path = model_path<br>        self.pose_detector = self._init_pose_detector()<br>        self.landmarks_list = []<br>    <br>    def _init_buffers(self) -&gt; dict:<br>        &quot;&quot;&quot;<br>        Initialize deque buffers for each of the 33 pose landmarks.<br>        Each buffer stores the last `sma_window` frames of landmark coordinates.<br>        <br>        Returns:<br>            dict: Dictionary mapping landmark index to deque buffer<br>        &quot;&quot;&quot;<br>        return {i: deque(maxlen=SMA_WINDOW) for i in range(33)}<br>    <br>    def _init_pose_detector(self) -&gt; mp.tasks.vision.PoseLandmarker:<br>        &quot;&quot;&quot;<br>        Initialize MediaPipe PoseLandmarker with VIDEO running mode.<br>        <br>        Returns:<br>            PoseLandmarker: Configured pose detection model<br>        &quot;&quot;&quot;<br>        BaseOptions = mp.tasks.BaseOptions<br>        PoseLandmarker = mp.tasks.vision.PoseLandmarker<br>        PoseLandmarkerOptions = mp.tasks.vision.PoseLandmarkerOptions<br>        VisionRunningMode = mp.tasks.vision.RunningMode<br>        <br>        options = PoseLandmarkerOptions(<br>            base_options=BaseOptions(model_asset_path=self.model_path),<br>            running_mode=VisionRunningMode.VIDEO<br>        )<br>        return PoseLandmarker.create_from_options(options)<br>    <br>    def _init_video_capture(self, video_path: str) -&gt; tuple:<br>        &quot;&quot;&quot;<br>        Initialize video capture and extract video properties.<br>        <br>        Args:<br>            video_path: Path to the video file<br>            <br>        Returns:<br>            tuple: (VideoCapture object, fps, frame_width, frame_height)<br>        &quot;&quot;&quot;<br>        cap = cv2.VideoCapture(video_path)<br>        fps = cap.get(cv2.CAP_PROP_FPS)<br>        frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))<br>        frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))<br>        return cap, fps, frame_width, frame_height<br>    <br>    def _init_writer(self, out_path, fourcc, fps, dimensions):<br>        return cv2.VideoWriter(out_path, fourcc, fps, dimensions)<br>    <br>    def _process_frame(self, image: np.ndarray, timestamp_ms: int) -&gt; tuple:<br>        &quot;&quot;&quot;<br>        Process a single frame through the pose detector.<br>        <br>        Args:<br>            image: Frame in RGB format (numpy array)<br>            timestamp_ms: Timestamp in milliseconds for video frame<br>            <br>        Returns:<br>            tuple: (detection_result, mp.Image)<br>        &quot;&quot;&quot;<br>        mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=image)<br>        detection_result = self.pose_detector.detect_for_video(mp_image, timestamp_ms)<br>        return detection_result, mp_image<br>    <br>    def transform_func(self, x, y, z, visibility, presence, idx):<br>        return x+0.25, y, z, visibility, presence<br>    <br>    def sma_transform_func(self, x, y, z, visibility, presence, landmark_buffers, idx):<br>        buffer = landmark_buffers[idx]<br>        buffer.append([x, y, z])<br>        if len(buffer) == buffer.maxlen:<br>            mean_x, mean_y, mean_z = np.mean(buffer, axis=0)<br>            return mean_x, mean_y, mean_z, visibility, presence<br>        else:<br>            return x, y, z, visibility, presence<br>        <br>    def _transform_landmarks(self, pose_landmarks_list: list, transform_func, landmark_buffers) -&gt; list:<br>        &quot;&quot;&quot;<br>        Applies transform_func to each landmark in each detected pose.<br><br>        Args:<br>            pose_landmarks_list: list of lists of landmarks (detection_result.pose_landmarks)<br>            transform_func: function that takes (x, y, z) and returns transformed (x, y, z)<br><br>        Returns:<br>            transformed_landmarks_list: list of lists of transformed landmarks as tuples (x, y, z)<br>        &quot;&quot;&quot;<br>        transformed_landmarks_list = []<br>        <br>        if not pose_landmarks_list:<br>            return transformed_landmarks_list<br>        <br>        for pose_landmarks in pose_landmarks_list:<br>            transformed_landmarks = []<br>            for i,landmark in enumerate(pose_landmarks):<br>                x, y, z, v, p = landmark.x, landmark.y, landmark.z, landmark.visibility, landmark.presence<br>                x_t, y_t, z_t, v_t, p_t = transform_func(x, y, z, v, p, landmark_buffers, idx=i)<br>                x_t1, y_t1, z_t1, v_t1, p_t1 = self.transform_func(x_t, y_t, z_t, v_t, p_t, idx=i)<br>                transformed_landmarks.append((x_t1, y_t1, z_t1, v_t1, p_t1))<br>            <br>            transformed_landmarks_list.append(transformed_landmarks)<br>            self.landmarks_list.append(transformed_landmarks)<br>        <br>        return transformed_landmarks_list<br>    <br>    def _create_landmark_proto(self, transformed_landmarks: list) -&gt; landmark_pb2.NormalizedLandmarkList:<br>        &quot;&quot;&quot;<br>        Convert transformed landmarks to MediaPipe protobuf format.<br>        <br>        Args:<br>            transformed_landmarks: List of transformed landmark tuples<br>            <br>        Returns:<br>            landmark_pb2.NormalizedLandmarkList: Protobuf representation of landmarks<br>        &quot;&quot;&quot;<br>        proto_landmarks = landmark_pb2.NormalizedLandmarkList()<br>        <br>        for pose_landmarks in transformed_landmarks:<br>            proto_landmarks.landmark.extend([<br>                landmark_pb2.NormalizedLandmark(<br>                    x=x, y=y, z=z, visibility=visibility, presence=presence<br>                ) for (x, y, z, visibility, presence) in pose_landmarks<br>            ])<br>        <br>        return proto_landmarks<br>    <br>    def draw_landmarks_on_image(self, rgb_image, proto_landmarks):<br>        &quot;&quot;&quot;<br>        Draw pose landmarks on the image given protobuf NormalizedLandmarkList.<br><br>        Args:<br>            rgb_image: Input RGB image as a numpy array.<br>            proto_landmarks: A landmark_pb2.NormalizedLandmarkList object of pose landmarks.<br><br>        Returns:<br>            annotated_image: Image with landmarks drawn.<br>        &quot;&quot;&quot;<br>        annotated_image = np.copy(rgb_image)<br><br>        if proto_landmarks is None or len(proto_landmarks.landmark) == 0:<br>            return annotated_image<br><br>        solutions.drawing_utils.draw_landmarks(<br>            annotated_image,<br>            proto_landmarks,<br>            solutions.pose.POSE_CONNECTIONS,<br>            solutions.drawing_styles.get_default_pose_landmarks_style()<br>        )<br>        return annotated_image<br>    <br>    def reset_buffers(self):<br>        &quot;&quot;&quot;Reset all landmark buffers. Call this before processing a new video.&quot;&quot;&quot;<br>        self.landmark_buffers = self._init_buffers()<br>        <br>    def process_video(self, video_path: str, out_path: str) -&gt; landmark_pb2.NormalizedLandmarkList:<br>        &quot;&quot;&quot;<br>        Process an entire video file and extract pose landmarks.<br>        <br>        Args:<br>            video_path: Path to the video file<br>            <br>        Returns:<br>            All extracted landmarks data of a single frame<br>        &quot;&quot;&quot;<br>        cap, fps, width, height = self._init_video_capture(video_path)<br>        fourcc = cv2.VideoWriter_fourcc(*&#39;mp4v&#39;)<br>        out = self._init_writer(out_path, fourcc, fps, (width, height))<br>        frame_count = 0<br>        buffers = self._init_buffers()<br>        try:<br>            while cap.isOpened():<br>                success, image = cap.read()<br>                if not success:<br>                    break<br>                # if(frame_count &gt; 20):<br>                #     break<br>                timestamp_ms = int(cap.get(cv2.CAP_PROP_POS_MSEC))<br>                image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br>                                <br>                detection_result, mp_image = self._process_frame(image_rgb, timestamp_ms)                <br>                <br>                if detection_result.pose_landmarks:<br>                    transformed_points = self._transform_landmarks(detection_result.pose_landmarks, self.sma_transform_func, buffers )<br>                    proto_landmarks = self._create_landmark_proto(transformed_points)<br>                    annotated_image = self.draw_landmarks_on_image(mp_image.numpy_view(), proto_landmarks)<br>                    annotated_image_bgr = cv2.cvtColor(annotated_image, cv2.COLOR_RGB2BGR)<br>                    out.write(annotated_image_bgr)<br>                frame_count += 1<br>        finally:<br>            cap.release()<br>            out.release()<br>        return proto_landmarks<br>    <br>    def get_all_landmarks(self):<br>        return self.landmarks_list</pre><h4>What the future holds</h4><p>MediaPipe used to provide smoothing options in older versions but the new version does not let us smooth out the landmarks. A python module is needed to work with the MediaPipe solutions for faster implementation of various filter algorithms.</p><p>As the field of pose estimation matures, the pipeline is shifting toward more modular and customizable architectures. Developers who embrace and contribute to well-documented Python modules for pose landmark smoothing will drive both research and real-world adoption forward. With the right community, resources, and standards, the future holds far more robust, jitter-free human pose tracking — fueling the next generation of computer vision applications.</p><p>Ready to level up? Next, we’ll implement and benchmark advanced filters — including Kalman, EMA, and One-Euro — so you can choose the best fit for your mission-critical pose estimation workflows. Stay tuned for more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcc03f462196" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Animated After-Splash Screen in Compose]]></title>
            <link>https://medium.com/@debasishraut.dev/custom-animated-after-splash-screen-in-compose-636702ccf6f0?source=rss-5503dc1080a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/636702ccf6f0</guid>
            <category><![CDATA[android-animations]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[splash-screen]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[side-effects]]></category>
            <dc:creator><![CDATA[Debasish Raut]]></dc:creator>
            <pubDate>Sat, 01 Nov 2025 13:09:44 GMT</pubDate>
            <atom:updated>2025-11-01T13:09:44.367Z</atom:updated>
            <content:encoded><![CDATA[<p>Mobile apps usually have more than one screens, and each screen has their own set of functionalities and behavior. Using XML Layouts we could achieve the separate behaviors entirely but it was soon noticed that having a lot of common components between activities can introduce architectural rigidity, code duplication, harder maintenance, and poor re-usability of code for the developers.</p><p>Navigation in Jetpack Compose refers to the process of moving between different screens or destinations within a Compose-based Android application. Take splash screens for example. The short interval that displays the app’s icon just as you open an app is called a system-level splash screen. And Then there are compose-level splash screens which we are going to implement. These composables are not linked to system and are just like any other composables but we will be controlling their screen-time using LaunchedEffect to introduce a delay before our compose SplashScreen dissapears.</p><p>LaunchedEffect is a side effect API that runs suspend functions (often navigation, network tasks, or time delays) after composition based on key changes.</p><p>Let’s go ahead and create a splash screen for that matter.</p><p>So to start, create a new package calledcomponents, and within it create package ui and within this create your file to hold the SplashScreen composable. For the graphics, we will be using the community developed <a href="https://www.figma.com/community/file/1385594739598175691">Calorie Tracker App Design Files</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tITUqXVIEySY0gK4jstvLg.png" /><figcaption>Calorie Tracker Design by <a href="https://www.figma.com/@3e548c78_9bd3_4">ItamiOMW</a></figcaption></figure><p>Open the Figma design file and identify separate elements: design page components page, and styles page(color palettes and typography) . To ensure consistent styling in your Compose app, extract the color values and typography styles from Figma and incorporate them as constants or theme values in your Compose code.</p><p>Create a new Empty Views Jetpack Compose Android Project. Go to Colors.kt and fill the values from the Style page in Figma to your Colors.kt file under the ui.theme package. Map each Figma color to a specific Material color role in your theme, ensuring each provides suitable contrast and adheres to accessibility guidelines. For example: use your green shade for primary, a dark shade for background, and a light neutral for surface. Always verify color accessibility before finalizing the palette. Or just copy paste from here 👇</p><pre>val DarkNight         = Color(0xFF0D0D0D)<br>val MintLeaf          = Color(0xFF49D199)<br>val MidnightBlue      = Color(0xFF242833)<br>val LavenderMist      = Color(0xFFAA9BD2)<br>val AshGrey           = Color(0xFF666666)<br>val CrimsonBlush      = Color(0xFFB24F58)<br>val SunsetOrange      = Color(0xFFCB7F5B)<br>val AquaGlow          = Color(0xFF41FFBB)<br>val EmeraldWave       = Color(0xFF2DAE77)<br>val LightSilver       = Color(0xFFB3B3B3)<br>val GraphiteShadow    = Color(0xFF656565)<br>val SilverMist        = Color(0xFFE6E6E6)<br>val SlateBlue         = Color(0xFF3E414D)<br>val SteelGrey         = Color(0xFF808080)<br>val SoftSky           = Color(0xFF90A6BA)<br><br>val PureWhite         = Color(0xFFFFFFFF)<br>val LeafGreen         = Color(0xFF35CC8C)<br>val SnowWhite         = Color(0xFFFFFFFF)<br>val CloudGrey         = Color(0xFFD9D9D9)<br>val RoseBloom         = Color(0xFFE56571)<br>val Sunbeam           = Color(0xFFFFA072)<br>val LightAqua         = Color(0xFF59FFC4)<br><br>val DeepMidnight      = Color(0xFF0D1220)<br>val FrostedGrey       = Color(0xFFF7F7F7)<br>val MistyGreen        = Color(0xFFDBFBED)<br>val PureCinder        = Color(0xFFCCCCCC)<br>val Charcoal          = Color(0xFF808080)<br>val SilverCloud       = Color(0xFFBFBFBF)<br>val MistyGreenLight   = Color(0xFFDBFBED)<br>val MintFog           = Color(0XFFE6FFE6)</pre><p>When creating your theme with darkColorScheme and lightColorScheme, assign your color values to specific Material roles based on their intended UI use. We remove the dynamic color lines because strict brand consistency is required. Dynamic color lines change the color basd on the wallpaper or the system theme, which makes the app more user-centrist but if our requirement deems it worthy, we shall have to comply.</p><p>Go ahead to the Theme.kt and paste this(also we won’t be needing the dynamic coloring so we need to remove those lines from the boiler plate code):</p><pre>import androidx.compose.foundation.isSystemInDarkTheme<br>import androidx.compose.material3.MaterialTheme<br>import androidx.compose.material3.darkColorScheme<br>import androidx.compose.material3.lightColorScheme<br>import androidx.compose.runtime.Composable<br><br>val DarkColorScheme = darkColorScheme(<br>    primary = LeafGreen,<br>    onPrimary = PureWhite,<br>    primaryContainer = MidnightBlue,<br>    onPrimaryContainer = SoftSky,<br>    inversePrimary = EmeraldWave,<br>    secondary = AquaGlow,<br>    onSecondary = DarkNight,<br>    secondaryContainer = LavenderMist,<br>    onSecondaryContainer = SlateBlue,<br>    tertiary = SunsetOrange,<br>    onTertiary = PureWhite,<br>    tertiaryContainer = CrimsonBlush,<br>    onTertiaryContainer = PureWhite,<br>    background = DarkNight,<br>    onBackground = LightSilver,<br>    surface = MidnightBlue,<br>    onSurface = LightSilver,<br>    surfaceVariant = GraphiteShadow,<br>    onSurfaceVariant = SilverMist,<br>    surfaceTint = MintLeaf,<br>    inverseSurface = AshGrey,<br>    inverseOnSurface = GraphiteShadow,<br>    error = RoseBloom,<br>    onError = PureWhite,<br>    errorContainer = Sunbeam,<br>    onErrorContainer = PureWhite,<br>    outline = SlateBlue,<br>    outlineVariant = SteelGrey,<br>    scrim = DeepMidnight,<br>    surfaceBright = SilverMist,<br>    surfaceContainer = MidnightBlue,<br>    surfaceContainerHigh = AshGrey,<br>    surfaceContainerHighest = PureCinder,<br>    surfaceContainerLow = SlateBlue,<br>    surfaceContainerLowest = AshGrey,<br>    surfaceDim = SilverMist<br>)<br><br>val LightColorScheme = lightColorScheme(<br>    primary = LeafGreen,<br>    onPrimary = PureWhite,<br>    primaryContainer = MistyGreen,<br>    onPrimaryContainer = DeepMidnight,<br>    inversePrimary = LightAqua,<br>    secondary = LightAqua,<br>    onSecondary = DeepMidnight,<br>    secondaryContainer = CloudGrey,<br>    onSecondaryContainer = MistyGreenLight,<br>    tertiary = Sunbeam,<br>    onTertiary = PureWhite,<br>    tertiaryContainer = RoseBloom,<br>    onTertiaryContainer = PureWhite,<br>    background = PureWhite,<br>    onBackground = DeepMidnight,<br>    surface = FrostedGrey,<br>    onSurface = DeepMidnight,<br>    surfaceVariant = SilverCloud,<br>    onSurfaceVariant = SilverCloud,<br>    surfaceTint = LeafGreen,<br>    inverseSurface = Charcoal,<br>    inverseOnSurface = PureWhite,<br>    error = RoseBloom,<br>    onError = PureWhite,<br>    errorContainer = Sunbeam,<br>    onErrorContainer = PureWhite,<br>    outline = Charcoal,<br>    outlineVariant = SilverCloud,<br>    scrim = DeepMidnight,<br>    surfaceBright = PureWhite,<br>    surfaceContainer = FrostedGrey,<br>    surfaceContainerHigh = CloudGrey,<br>    surfaceContainerHighest = MistyGreen,<br>    surfaceContainerLow = SilverCloud,<br>    surfaceContainerLowest = PureWhite,<br>    surfaceDim = FrostedGrey<br>)<br><br>@Composable<br>fun ComposeNavTheme(<br>    darkTheme: Boolean = isSystemInDarkTheme(),<br>    // Dynamic color is available on Android 12+<br>    dynamicColor: Boolean = true,<br>    content: @Composable () -&gt; Unit<br>) {<br>    val colorScheme = when {<br>        darkTheme -&gt; DarkColorScheme<br>        else -&gt; LightColorScheme<br>    }<br><br>    MaterialTheme(<br>        colorScheme = colorScheme,<br>        typography = Typography,<br>        content = content<br>    )<br>}</pre><p>Let’s create our Splash Screen Graphics. It is available from the figma file. I will show you how to get the design file this one time and you can follow along for the rest of the imports from the figma file to android.</p><p>In the design file, under the components page you will find the logo. We need to export icons and components from Figma in SVG format, ensuring correct art-board size and proper path centering, then import them into our Android project via Resource Manager. Always review exported assets for device compatibility and scaling issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*CgVJhRvS-lmbrQiGoBwjiw.png" /></figure><p>Double click the logo until you see a 100x100 dimension boundary. You can also select the component using the Layers tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*bjC5QRLcMy4FNGSu6d85-w.png" /></figure><p>Then go to the right side design tab and scroll down to the very last until you see the Export group. Export the icon as svg from here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*hH5IKhwwmYjQhLMNhl5RRg.png" /></figure><p>Now add this resource as a drawable, just go to the resource manager and hit the + icon and follow along.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*zetjFEq_J-nwSvoJd5yUDQ.png" /></figure><p>Next, let’s create the SplashScreen.kt Composable function in the package components.screens .</p><pre>@Composable<br>fun SplashScreen(<br>    modifier: Modifier = Modifier,<br>) {<br>    Box(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .background(MaterialTheme.colorScheme.background),<br>        contentAlignment = Alignment.Center<br>    ) {<br>        Column (horizontalAlignment = Alignment.CenterHorizontally) {<br>            Icon(<br>                painter = painterResource(R.drawable.app_logo),<br>                contentDescription = &quot;app logo&quot;,<br>                tint = MaterialTheme.colorScheme.primary,<br>            )<br>        }<br>    }<br>}</pre><p>To show a splash screen as the app opens, use Android’s system SplashScreen API or theme-based manifest splash. But if you want a splash screen <em>within</em> your Compose content after the system-level splash screen has ended, LaunchedEffect can be used to orchestrate timed navigation after Compose is visible.</p><p>We Build the SplashScreen composable using MaterialTheme values for background and icon colors to ensure consistency with the app’s overall theme.</p><p>Next let’s go ahead and provide a SplashOut function parameter to handle what happens after the splash time out and let’s use the LaunchedEffect to configure our SplashScreen.</p><pre>@Composable<br>fun SplashScreen(<br>    onSplashEnd: () -&gt; Unit,<br>    modifier: Modifier = Modifier,<br>) {<br>    LaunchedEffect (Unit) {<br>        delay(200)<br>        onSplashEnd()<br>    }<br>    Box(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .background(MaterialTheme.colorScheme.background),<br>        contentAlignment = Alignment.Center<br>    ) {<br>        Column (horizontalAlignment = Alignment.CenterHorizontally) {<br>            Icon(<br>                painter = painterResource(R.drawable.app_logo),<br>                contentDescription = &quot;app logo&quot;,<br>                tint = MaterialTheme.colorScheme.primary,<br>            )<br>        }<br>    }<br>}</pre><p>We can call this in our app file. I like to separate our app logic into a file and keep the Main Activity clean.</p><p>MainActivity.kt</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContent {<br>            ComposeNavTheme {<br>                ComposeNavApp()<br>            }<br>        }<br>    }<br>}</pre><p>ComposeNavApp.kt</p><pre>@Composable<br>fun ComposeNavApp() {<br>    var isSplashinTime by remember { mutableStateOf(true) }<br>    if (isSplashinTime) {<br>        SplashScreen(onSplashEnd = { isSplashinTime = false })<br>    } else {<br>        Landing()<br>    }<br>}</pre><p>Here, the Composable Landing() is only a placeholder for now, a simple composable containing a Text composable that displays “Hello World” message. We create a Boolean State variable called isSpalshinTime and use it to load the splash screen or the Landing page based on the user activity.</p><p>Currently the splash screen functions as it should but it looks bland. What’s a splash screen without all the flashy animations. We will settle for some simple animations. We would like the green apple logo to enlarge itself in a popping motion and rotate slightly to bring about liveliness to our animation. For that we need to animate the size and the rotation angle of the object and apply spring animations to it for that popping effect. We would also like the screen to fade out after the just before the onSplashEnd function is triggered.</p><p>So we take three state variables, the size, the tilt and the alpha values.</p><pre>@Composable<br>fun SplashScreen(<br>    onSplashEnd: () -&gt; Unit,<br>    modifier: Modifier = Modifier,<br>) {<br>    val isFirstTimeVisit = remember { isFirstTimeVisit() }<br>    val animatedSize = remember { Animatable(96f) }<br>    val animatedTilt = remember { Animatable(0f) }<br>    val animatedAlpha = remember { Animatable(1f) }<br>    LaunchedEffect (Unit) {<br>        delay(200)<br>        animatedSize.animateTo(<br>            targetValue = 192f,<br>            animationSpec = spring(<br>                stiffness = Spring.StiffnessMedium,<br>                dampingRatio = Spring.DampingRatioMediumBouncy<br>            )<br>        )<br>        animatedTilt.animateTo(<br>            targetValue = 15f,<br>            animationSpec = spring(<br>                stiffness = Spring.StiffnessLow,<br>                dampingRatio = Spring.DampingRatioNoBouncy<br>            )<br>        )<br>        animatedTilt.animateTo(<br>            targetValue = 0f,<br>            animationSpec = spring(<br>                stiffness = Spring.StiffnessMedium,<br>                dampingRatio = Spring.DampingRatioMediumBouncy<br>            )<br>        )<br>        delay(1000)<br>        animatedAlpha.animateTo(<br>            targetValue = 0f,<br>            animationSpec = spring(stiffness = Spring.StiffnessLow)<br>        )<br>        onSplashEnd()<br>    }<br>    Box(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .graphicsLayer { alpha = animatedAlpha.value }<br>            .background(MaterialTheme.colorScheme.background),<br>        contentAlignment = Alignment.Center<br>    ) {<br>        Column (horizontalAlignment = Alignment.CenterHorizontally) {<br>            Icon(<br>                painter = painterResource(R.drawable.app_logo),<br>                contentDescription = &quot;app logo&quot;,<br>                tint = MaterialTheme.colorScheme.primary,<br>                modifier = Modifier<br>                    .size(animatedSize.value.dp)<br>                    .graphicsLayer {<br>                        rotationZ = animatedTilt.value<br>                    }<br>            )<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*RJtgHwnmSQmpDVHTaP4-AQ.gif" /></figure><p>We implemented a Compose-level splash screen that leverages LaunchedEffect to manage a timed transition based on state changes. While this allows for smooth in-app navigation from the splash to the main landing page, remember that true app launch visuals — such as the system-level splash screen — should be handled using Android’s theme or SplashScreen API for best user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=636702ccf6f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern UIs with Jetpack Compose: Your Complete Guide to Background Modifiers and Beautiful Visual…]]></title>
            <link>https://medium.com/@debasishraut.dev/modern-uis-with-jetpack-compose-your-complete-guide-to-background-modifiers-and-beautiful-visual-d45cd26984c3?source=rss-5503dc1080a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d45cd26984c3</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[animated-backgrounds]]></category>
            <category><![CDATA[android-ui]]></category>
            <dc:creator><![CDATA[Debasish Raut]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 05:31:38 GMT</pubDate>
            <atom:updated>2025-10-24T10:35:26.301Z</atom:updated>
            <content:encoded><![CDATA[<h3>Modern UIs with Jetpack Compose: Your Complete Guide to Background Modifiers and Beautiful Visual Effects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcSZwLBwRnWlCztoNotu2g.png" /></figure><p>In Jetpack Compose, modifiers are powerful, reusable building blocks that let you change how your UI components (composables) look, behave, and interact. It is an ordered, immutable collection of modifier elements (Modifier.Element) used to decorate, transform, or extend the behavior of UI components. Technically, it is an interface, following the <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">chain of responsibility pattern</a>. In the following sections we will explore the .background extension function of the Modifier Interface. The Modifier interface itself does not have built-in decoration or behavior—it provides the framework for chaining and combining elements. Functions like Modifier.background(...) are extension functions that create and return a new Modifier containing a specific Modifier.Element inside the chain. Internally, these factory methods construct a <em>background modifier element</em> and combine it with the current modifier chain using then. background() acts as a factory, abstracting away the process of creating the correct modifier element and chaining it.</p><h3>Backgrounds: The Canvas of UI Design</h3><p>In UI design, backgrounds are the foundational layer — the canvas on which all other visual elements are placed. Just as a painter begins with a blank surface before adding color, form, and detail, a digital interface starts with its background. This layer sets the mood, context, and visual boundaries for the entire design. A thoughtfully chosen background can evoke emotion, guide user focus, and establish brand identity before any text or icon appears.</p><p>Backgrounds also play a practical role: they provide contrast for content, help organize layout, and create visual hierarchy. Whether it’s a solid color, a gradient, or a textured image, the background is the silent partner that lets the rest of the UI shine. In Compose, backgrounds are often the first modifier applied, paving the way for padding, shapes, and interactive elements to build upon a visually coherent base.</p><h3>Background Modifier in Jetpack Compose</h3><p>The background modifier in Jetpack Compose lets you easily add color, gradients, or even custom brushes behind your composables. It is typically the first modifier in a chain, ensuring that the background is drawn before other effects like padding or borders. This approach mirrors the layering in traditional art—starting with the base and building up details.</p><h4>Simple Usage Example</h4><pre>@Composable<br>fun SimpleBackgroundBox() {<br>    Box(<br>        modifier = Modifier<br>            .size(120.dp)<br>            .background(Color.LightGray)<br>    ) {<br>        // TODO: Add Composables Here<br>    }<br>}</pre><p>In this simple example, the Box composable gets a light gray background, serving as the visual foundation for any content placed inside. You can replace Color.LightGray with gradients or custom brushes for more advanced effects that we will explore as we delve deeper into the function and its overloaded counterparts.</p><h4>Modifier.background(color: Color, shape: Shape)</h4><p>Modifier.background(color: Color, shape: Shape) in Jetpack Compose lets you easily add colored, shaped backgrounds to UI elements using a concise, chainable API. It’s an extension function for the Modifier interface, supporting rectangles and custom shapes, making sophisticated, visually appealing designs straightforward and essential for establishing strong UI context in your Android apps.</p><h4>Before we begin…</h4><p>Before we begin, I just want to make sure you can follow along so I want to specify my file organization structure. We have created separate packages for each of our components and within these packages we have the actual files that are simply composable functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*Cvm5O2dppk0-5uAlAChoXA.png" /><figcaption>example file structure</figcaption></figure><p>So we can start by creating a components package, and within it we create another package for heading_text which has two files:</p><p><strong>HeadingText.kt</strong></p><pre>@Composable<br>fun HeadingText(text: String) {<br>    SolidBackground {<br>        Text(text, modifier = Modifier<br>            .padding(24.dp, 6.dp),<br>            fontWeight = FontWeight.ExtraBold,<br>            color = Color(0XFFEDFAFC) // Color: Azure Web White<br>        )<br>    }<br>}</pre><p><strong>HeadingTextPreview.kt</strong></p><pre>fun HeadingTextPreview() {<br>    Column {<br>        HeadingText(&quot;Log in to your account&quot;)<br>    }<br>}</pre><h4>Simple Backgrounds</h4><p>Next we need to create the container components so we create a package under components, called containers. Within containers, we have another package called solid that houses the file solid_bg.kt:</p><pre>@Composable<br>fun SolidBackground(<br>    modifier: Modifier = Modifier,<br>    children: @Composable () -&gt; Unit<br>) {<br>    Box(<br>        modifier = modifier.then(<br>            Modifier<br>                .background(<br>                    color=Color(0XFF3F6634), // Color: Hunter Green<br>                    shape=RoundedCornerShape(12.dp)<br>            )<br>        )<br>    ) {<br>        children()<br>    }<br>}</pre><p>Notice how this is a container component and thus takes in a children parameter which is nothing but another composable function. We will use this structure to demonstrate much of the background function and its overloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*JIQPKSGbyIxqTAk8YL7-Vw.png" /></figure><p>I believe we should unpack the “shape” parameter that we dropped in the .background function. Jetpack Compose provides some foundational shapes and other more complex shapes can be create using custom classes that implements the Shape interface. For now, let’s take a look at the foundational shape options that we have.</p><h4>RectangleShape</h4><ul><li><em>Plain rectangle; sharp square corners.</em><br>Modifier.background(Color.Blue, RectangleShape)</li></ul><h4>CircleShape</h4><ul><li><em>Perfect circle background clipped to the smallest edge.</em><br>Modifier.background(Color.Green, CircleShape)</li></ul><h4>RoundedCornerShape</h4><ul><li><em>Rectangle with rounded corners (configurable radius).</em><br>Modifier.background(Color.Red, RoundedCornerShape(24.dp))</li></ul><h4>CutCornerShape</h4><ul><li><em>Rectangle with “cut-off” corners (configurable size).</em><br>Modifier.background(Color.Yellow, CutCornerShape(12.dp))</li></ul><h4>AbsoluteRoundedCornerShape</h4><ul><li><em>Similar to RoundedCornerShape but ignores layout direction (useful for fixed shapes in bidirectional layouts).</em><br>Modifier.background(Color.Cyan, AbsoluteRoundedCornerShape(18.dp))</li></ul><h4>AbsoluteCutCornerShape</h4><ul><li><em>“Cut-off” corners, but ignores layout direction (good for always-left/right layouts).</em><br>Modifier.background(Color.Magenta, AbsoluteCutCornerShape(10.dp))</li></ul><p>We will see examples of these shapes as we move ahead in our exploration of backgrounds.</p><h3>Gradient Backgrounds</h3><p>Draws the given shape with the specified brush (gradient, pattern, etc.) and alpha behind the content.</p><p>Function Signature:</p><p><a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier">Modifier</a>.<a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).background(androidx.compose.ui.graphics.Brush,androidx.compose.ui.graphics.Shape,kotlin.Float)">background</a>(<br> brush: <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/graphics/Brush">Brush</a>,<br> shape: <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/graphics/Shape">Shape</a>,<br> alpha: @<a href="https://developer.android.com/reference/kotlin/androidx/annotation/FloatRange">FloatRange</a>(from = 0.0, to = 1.0) <a href="https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-float/index.html">Float</a><br> )</p><p>Example:</p><pre>Box(<br>        modifier = modifier.then(<br>            Modifier<br>                .background(<br>                    brush = Brush.verticalGradient(<br>                        colors = listOf(<br>                            Color(0XFFFA7E61),<br>                            Color(0xFFFAFF7F)<br>                        )),<br>                    shape = CutCornerShape(4.dp),<br>                    alpha = 0.8f<br>                )<br>        )<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*v8RvF0gRC2MaslOmDhsKvw.png" /></figure><p>The brush parameter in the .background() modifier for Jetpack Compose allows you to use advanced graphics for backgrounds, like gradients and shaders, rather than a solid color.<br>A Brush in Compose describes how something is drawn on the screen, determining the color(s) and pattern in a drawing area (rectangle, circle, etc.).</p><p>According to the official API documentation, you can use:</p><ul><li>Brush.horizontalGradient(colors: List&lt;Color&gt;)</li><li>Brush.verticalGradient(colors: List&lt;Color&gt;)</li><li>Brush.linearGradient(colors: List&lt;Color&gt;, start: Offset, end: Offset)</li><li>Brush.radialGradient(colors: List&lt;Color&gt;, center: Offset, radius: Float)</li><li>Brush.sweepGradient(colors: List&lt;Color&gt;, center: Offset)</li><li>Brush.solidColor(color: Color)</li></ul><p>Let’s explore the brush some more:</p><h4>Horizontal Gradient</h4><p>In our package .components.containers.horizontal_background we can define our composable in HorizontalGradSimple.kt file. The composable will take a modifier parameter and children to house the composables that need the horizontal gradient as their background.</p><pre>@Composable<br>fun HorizontalGradSimple(<br>    modifier: Modifier = Modifier,<br>    children: @Composable () -&gt; Unit<br>) {<br>    Box(modifier = modifier.then(<br>        Modifier<br>            .background(<br>                brush = Brush.horizontalGradient(<br>                    colors = listOf(Color(0xffE899DC), Color(0xffA997DF), Color(0xffD81E5B))<br>                ),<br>                shape = RoundedCornerShape(12.dp)<br>            )<br>    )) {<br>        children()<br>    }<br>}</pre><p>Notice how we have chained the modifier using the then function. Modifier class allows us to chain multiple modifiers together using the then() function. When you chain modifiers, each one is applied in sequence to the composable, allowing you to combine multiple transformations, size constraints, padding, background colors, gestures, and more. The then() function specifically enables merging two modifiers into one—either appending new behavior or overriding certain properties from the previous modifiers.</p><p>We can use this component by calling the composable in our Activity classes.</p><pre>. . . <br><br>HorizontalGradSimple {<br>            Text(text, modifier = Modifier<br>                .padding(24.dp, 6.dp),<br>                fontWeight = FontWeight.ExtraBold,<br>                color = Color(0XFFEDFAFC),<br>                textAlign = TextAlign.Center<br>            )<br>        }<br>. . . </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*7xwwonmOc4mjcMkmMcHVdw.png" /></figure><p>We can even control how the gradient is composed by supplying a Pair of Float with Color values where the float value indicates where the color gradients start to blend in with the other colors:</p><pre>fun HorizontalGradientWithStops(<br>    modifier: Modifier,<br>    children: @Composable () -&gt; Unit<br>) {<br>    Box (<br>        modifier = modifier.then(<br>            Modifier.background(<br>                brush = Brush.horizontalGradient(<br>                    colorStops = arrayOf(<br>                        0.0f to Color(0xFF2446C2),<br>                        0.4f to Color(0xFF382458),<br>                        1.0f to Color(0xFFB51FBF)<br>                    )<br>                ),<br>                shape = CutCornerShape(50.dp)<br>            )<br>        )<br>    ){<br>        children()<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*LM1TBnclWdKAkeCgNXZeCQ.png" /></figure><p>If you get more curious, we can even create an animation based on the stop color’s values, increasing and decreasing them in an oscillation motion. Better yet, we can just apply the same values to two stop colors and we will have a more distinct separation of colors with minimal blending.</p><pre>@Composable<br>fun HorizontalGradientWithAnimatedStops(<br>    modifier: Modifier,<br>    children: @Composable () -&gt; Unit<br>) {<br>    val infiniteTransition = rememberInfiniteTransition()<br>    val stopValue by infiniteTransition.animateFloat(<br>        initialValue = 0.2f,<br>        targetValue = 0.8f,<br>        animationSpec = infiniteRepeatable(<br>            animation = tween(durationMillis = 2000, easing = EaseInOut),<br>            repeatMode = RepeatMode.Reverse<br>        )<br>    )<br>    Box (<br>        modifier = modifier.then(<br>            Modifier.background(<br>                brush = Brush.horizontalGradient(<br>                    colorStops = arrayOf(<br>                        0.0f to Color(0xFF2446C2),<br>                        stopValue to Color(0xFF382458),<br>                        stopValue to Color(0xFFB51FBF)<br>                    )<br>                ),<br>                shape = CutCornerShape(50.dp)<br>            )<br>        )<br>    ){<br>        children()<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*ucOGeBOhDZY5Rv3waVH8dQ.gif" /></figure><p>All the gradients have an overloaded function that takes in a Pair&lt;Float, Color&gt; values for color stops instead of a list of Colors objects.</p><h4>Radial Gradient</h4><p>Some amazing effects unlock when you start playing with radial gradients. They can be as simple as you want:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*_vp-dFCOZcK1FK-X2EoDXg.png" /></figure><p>or as mind boggling and you can make them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*coPAdz3uZhkWehEb_nF6Rw.png" /></figure><pre>@Composable<br>fun RadialGradientSimple(<br>    modifier: Modifier,<br>    children: @Composable () -&gt; Unit<br>) {<br><br>    Box (<br>        modifier = modifier.then(<br>            Modifier.background(<br>                brush = Brush.radialGradient(<br>                    colors = listOf(<br>                        Color(0xFF2DEF9F),<br>                        Color(0xFFC8E85A),<br>                        Color(0xFFFFD026),<br>                    ),<br>                   radius = 10.0f,<br>                   tileMode = TileMode.Repeated<br>                ),<br>                shape = RoundedCornerShape(3.dp)<br>            )<br>        )<br>    ){<br>        children()<br>    }<br>}</pre><h4>Linear Gradient</h4><p>Linear gradient distinguishes itself from horizontalGradient class by allowing the griadient to flow from any direction. To control the angle of gradient flow, we can specify the start and end values which are Offset class objects. Offset class objects take two float values as their x and y co-ordinate and the angle of flow is from the start towards the end point.</p><pre>@Composable<br>fun LinearGradientSimple(<br>    modifier: Modifier,<br>    children: @Composable () -&gt; Unit) {<br>    Box(<br>        modifier = modifier.then(<br>            Modifier<br>                .padding(2.dp)<br>                .background(<br>                    brush = Brush.linearGradient(<br>                        colorStops = arrayOf(<br>                            0.0f to Color(0xFF63FF63),<br>                            0.6f to Color(0xFFFF5E5E),<br>                            0.6f to Color(0xFF309BC7)<br>                        ),<br>                        start = Offset(0.0f, 0.0f),<br>                        end = Offset(496.0f, 90.0f)<br>                    ),<br>                    shape = RectangleShape<br>                )<br>        ),<br><br>    ) {<br>        children()<br>    }<br>}</pre><p>As a result we can achieve some interesting results using gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*ECJQewCP-ketOwP-blsuNA.png" /></figure><p>Before we dive into clipping of backgrounds, I’d like to expand upon the topic of <strong>Custom Shapes</strong>. Custom Shapes are, afterall, what makes the clipping of background worthwhile. In Jetpack Compose, custom shapes are no longer as easy as creating a new drawable from a vector that the UI Designer had made. While there is a way to use vector drawables, they won’t work in clipping the background. For that we need truly compose native shapes. So on we go towards the long and hard way to create custom shapes.</p><p>If you take a look at the shape called RectangleShape in your kotlin code, you can see how this shape is an implementation of the Shape interface that overrides the createOutline funtion. That is all it takes to create custom shapes. But the complexity starts here. With no way to visualize your designs, you are left with functions and your imagination using which you have to create awesome custom shapes that your UI Team has made after they returned from their creative blockage vacation.</p><p>It feels like making art in Illustrator — using the commandline.</p><h4>Path to Custom Shapes</h4><p>Creating Custom Shapes starts with implementing the Shape interface.</p><pre>interface Shape {<br>    /**<br>     * Creates [Outline] of this shape for the given [size].<br>     *<br>     * @param size the size of the shape boundary.<br>     * @param layoutDirection the current layout direction.<br>     * @param density the current density of the screen.<br>     *<br>     * @return [Outline] of this shape for the given [size].<br>     */<br>    fun createOutline(size: Size, layoutDirection: LayoutDirection, density: Density): Outline<br>}</pre><p>As a simple example, we create a Custom Rounded Rectangle:</p><pre>object CustomRoundedRectangleShape : Shape {<br>    override fun createOutline(<br>        size: Size,<br>        layoutDirection: LayoutDirection,<br>        density: Density<br>    ): Outline {<br>        return Outline.Rounded(<br>            roundRect = RoundRect(<br>                left = 0.0f,<br>                top = 0.0f,<br>                right = size.width,<br>                bottom = size.height,<br>                topLeftCornerRadius = CornerRadius(20.0f, 20.0f),<br>                topRightCornerRadius = CornerRadius(50.0f, 50.0f),<br>                bottomRightCornerRadius = CornerRadius(20.0f, 20.0f),<br>                bottomLeftCornerRadius = CornerRadius(50.0f, 50.0f),<br>            )<br>        )<br>    }<br>    override fun toString(): String = &quot;CustomRoundedRectangleShape&quot;<br>}<br> <br><br> . . .<br><br>Box(<br>        modifier = modifier.then(<br>            Modifier<br>                .padding(2.dp)<br>                .background(<br>                    brush = Brush.linearGradient(<br>                        colorStops = arrayOf(<br>                            0.0f to Color(0xFF63FF63),<br>                            0.6f to Color(0xFFFF5E5E),<br>                            0.6f to Color(0xFF309BC7)<br>                        ),<br>                        start = Offset(0.0f, 0.0f),<br>                        end = Offset(496.0f, 90.0f)<br>                    ),<br>                    shape = CustomRoundedRectangleShape<br>                )<br>        ),<br><br>    ) {<br>        children()<br>    }<br><br> . . . </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*1rc7gSgfnrJa9hvuZn2XAQ.png" /></figure><p>Next we go ahead creating complex shapes. Non standard shapes are more common in modern apps than you’d think. I came across a stack exchange post asking about a button shape shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*FgUCpAaoKf6a_Naw6aKbHw.png" /></figure><p>Such shapes can be created using native composables for optimal performance.</p><p>There are several ways to create custom shapes in Compose.</p><h4>GenericShape Class</h4><pre>class GenericShape : Shape</pre><p>The GenericShape class implements Shape interface and creates a shape using Path builder. We will write a function that uses this class to create a hexagonal shape. Further, we will use this shape to clip our component to contain it within this hexagon.</p><p>A hexagon is a six sided shape where the shape line bends at 60 degrees for six consecutive terms. Note that this description of the hexagonal shape is how we reached our code logic of drawing the shape in the first place. For the calculations we will need the height, width, radius, and the center point. Given below is an implementation of the said GenericShape composable.</p><pre>@Composable<br>fun HexagonGeneric(<br>    children : @Composable () -&gt; Unit<br>) {<br>    val hexagon = GenericShape {<br>        size, _ -&gt;<br>        val width = size.width<br>        val height = size.height<br>        val radius = minOf(width, height) / 2f<br>        val centerX = width / 2f<br>        val centerY = height / 2f<br><br>        for (i in 0..5) {<br>            val angleDeg = 60f * i - 30f<br>            val angleRad = Math.toRadians(angleDeg.toDouble())<br>            val x = (centerX + radius * cos(angleRad)).toFloat()<br>            val y = (centerY + radius * sin(angleRad)).toFloat()<br>            if (i == 0) {<br>                moveTo(x, y)<br>            } else {<br>                lineTo(x, y)<br>            }<br>        }<br>    }<br>    Box(<br>        modifier = Modifier<br>            .size(100.dp)<br>            .clip(hexagon)<br>            .background(Color(0xFFFF5913)),<br>        contentAlignment = Alignment.Center<br>    ) {<br>        children()<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*W3ELtvS79oBSdZahQtIzxw.png" /></figure><p>An easier and recommended way to create geometric polygons is by using the drawing method drawWithCache and creating our desired polygons within it.</p><h4>Exploring Animation Modifiers</h4><p>Ofcourse there will be animated designs thrown your way. Nobody can escape the animated designs.</p><p>The most common and simple animation out there is animating the visibility of an object. At one point in time it is there, and the next moment, it is gone! Black magic at work here. But wait, there is a simple explanation:</p><h4>AnimatedVisibility</h4><blockquote><a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#AnimatedVisibility(kotlin.Boolean,androidx.compose.ui.Modifier,androidx.compose.animation.EnterTransition,androidx.compose.animation.ExitTransition,kotlin.String,kotlin.Function1)">AnimatedVisibility</a> composable animates the appearance and disappearance of its content, as <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#AnimatedVisibility(kotlin.Boolean,androidx.compose.ui.Modifier,androidx.compose.animation.EnterTransition,androidx.compose.animation.ExitTransition,kotlin.String,kotlin.Function1)">visible</a> value changes. Different <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/EnterTransition">EnterTransition</a>s and <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/ExitTransition">ExitTransition</a>s can be defined in <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#AnimatedVisibility(kotlin.Boolean,androidx.compose.ui.Modifier,androidx.compose.animation.EnterTransition,androidx.compose.animation.ExitTransition,kotlin.String,kotlin.Function1)">enter</a> and <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#AnimatedVisibility(kotlin.Boolean,androidx.compose.ui.Modifier,androidx.compose.animation.EnterTransition,androidx.compose.animation.ExitTransition,kotlin.String,kotlin.Function1)">exit</a> for the appearance and disappearance animation.</blockquote><p>AnimatedVisibility composable takes a visibility boolean and enter and exit behaviour and shows the enter behaviour while the visibility value is true and shows the exit behaviour otherwise.</p><p>Let’s look at the code to better our understanding:</p><pre>@Composable<br>fun SimpleAnimatedContainer(<br>    modifier: Modifier = Modifier,<br>    children: @Composable () -&gt; Unit<br>) {<br>    var visible by remember { mutableStateOf(true) }<br>    Box(<br>        modifier = modifier.then(<br>            Modifier<br>                .fillMaxHeight()<br>                .fillMaxWidth()<br>                .clickable {<br>                    visible = !visible<br>                }<br>        )<br>    ) {<br>        AnimatedVisibility (<br>            visible = visible,<br>            modifier = Modifier.align(Alignment.Center),<br>            enter = fadeIn(),<br>            exit = fadeOut(animationSpec = tween (200)) + scaleOut(),<br>        ){<br>            Box(<br>                Modifier.background(Color(0xff123123), shape = RoundedCornerShape(12.dp))<br>                    .height(100.dp)<br>                    .fillMaxWidth(),<br>                contentAlignment = Alignment.Center<br>            ) {<br>                children()<br>            }<br>        }<br>    }<br>}</pre><p>Things to note here:</p><ul><li>We declare a state called visible to store the state of our component’s visibility. We toggle the state visible in the parent container’s modifier function clickable.</li><li>We use this state to control the AnimatedVisibility composable’s behaviour.</li><li>In the modifiers of AnimatedVisiblity, we mention the EnterTransition and ExitTransition functions. Note how these functions can be added using arithmetic operators.</li><li>There are 4 types of <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/EnterTransition">EnterTransition</a> and <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/ExitTransition">ExitTransition</a>: Fade, Expand/Shrink, Scale and Slide.</li></ul><p><a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/EnterTransition">EnterTransition</a> defines how an <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#AnimatedVisibility(kotlin.Boolean,androidx.compose.ui.Modifier,androidx.compose.animation.EnterTransition,androidx.compose.animation.ExitTransition,kotlin.String,kotlin.Function1)">AnimatedVisibility</a> Composable appears on screen as it becomes visible. The 4 categories of EnterTransitions available are:</p><ol><li>fade: <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#fadeIn(androidx.compose.animation.core.FiniteAnimationSpec,kotlin.Float)">fadeIn</a></li><li>scale: <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#scaleIn(androidx.compose.animation.core.FiniteAnimationSpec,kotlin.Float,androidx.compose.ui.graphics.TransformOrigin)">scaleIn</a></li><li>slide: <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#slideIn(androidx.compose.animation.core.FiniteAnimationSpec,kotlin.Function1)">slideIn</a>, <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#slideInHorizontally(androidx.compose.animation.core.FiniteAnimationSpec,kotlin.Function1)">slideInHorizontally</a>, <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#slideInVertically(androidx.compose.animation.core.FiniteAnimationSpec,kotlin.Function1)">slideInVertically</a></li><li>expand: <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#expandIn(androidx.compose.animation.core.FiniteAnimationSpec,androidx.compose.ui.Alignment,kotlin.Boolean,kotlin.Function1)">expandIn</a>, <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#expandHorizontally(androidx.compose.animation.core.FiniteAnimationSpec,androidx.compose.ui.Alignment.Horizontal,kotlin.Boolean,kotlin.Function1)">expandHorizontally</a>, <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#expandVertically(androidx.compose.animation.core.FiniteAnimationSpec,androidx.compose.ui.Alignment.Vertical,kotlin.Boolean,kotlin.Function1)">expandVertically</a></li></ol><p><a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/EnterTransition#None()">EnterTransition.None</a> can be used when no enter transition is desired. Different <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/EnterTransition">EnterTransition</a>s can be combined using plus operator.</p><p>As you might imagine ExitTransition also has similar categorical extensions:</p><ol><li>fade: <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#fadeOut(androidx.compose.animation.core.FiniteAnimationSpec,kotlin.Float)">fadeOut</a></li><li>scale: <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#scaleOut(androidx.compose.animation.core.FiniteAnimationSpec,kotlin.Float,androidx.compose.ui.graphics.TransformOrigin)">scaleOut</a></li><li>slide: <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#slideOut(androidx.compose.animation.core.FiniteAnimationSpec,kotlin.Function1)">slideOut</a>, <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#slideOutHorizontally(androidx.compose.animation.core.FiniteAnimationSpec,kotlin.Function1)">slideOutHorizontally</a>, <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#slideOutVertically(androidx.compose.animation.core.FiniteAnimationSpec,kotlin.Function1)">slideOutVertically</a></li><li>shrink: <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#shrinkOut(androidx.compose.animation.core.FiniteAnimationSpec,androidx.compose.ui.Alignment,kotlin.Boolean,kotlin.Function1)">shrinkOut</a>, <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#shrinkHorizontally(androidx.compose.animation.core.FiniteAnimationSpec,androidx.compose.ui.Alignment.Horizontal,kotlin.Boolean,kotlin.Function1)">shrinkHorizontally</a>, <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/package-summary#shrinkVertically(androidx.compose.animation.core.FiniteAnimationSpec,androidx.compose.ui.Alignment.Vertical,kotlin.Boolean,kotlin.Function1)">shrinkVertically</a></li></ol><p><a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/ExitTransition#None()">ExitTransition.None</a> can be used when no exit transition is desired.</p><p>Apart from these functions, we can also create custom transition functions. Custom enter/exit animations can be created using the Transition &lt;EnterExitState&gt; object from the <a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/AnimatedVisibilityScope">AnimatedVisibilityScope</a> (i.e.<a href="https://developer.android.com/reference/kotlin/androidx/compose/animation/AnimatedVisibilityScope#transition()">AnimatedVisibilityScope.transition</a>).</p><h4>Modifier.animateEnterExit</h4><p>Now what if you want to have different animations for parent and child. Ofcourse you need to use .animateEnterExit Modifier!</p><p>Consider a custom in-app notification, not the notification you create using NotificationManager, this is a custom app-specific notification which has amazing animations the default notifications can only dream of. Yes, we can create that using this modifier that enables us to handle multi-faceted animations.</p><pre>@Composable<br>fun CustomAnimNotification(<br>    modifier: Modifier = Modifier<br>) {<br>    var visible by remember { mutableStateOf(true) }<br>    Box(<br>        modifier = modifier.then(<br>            Modifier<br>                .fillMaxHeight()<br>                .fillMaxWidth()<br>                .clickable {<br>                    visible = !visible<br>                }<br>        )<br>    ) {<br>        AnimatedVisibility (<br>            visible = visible,<br>            enter = fadeIn(),<br>            exit = fadeOut()<br>        ) {<br>            Box(<br>                Modifier<br>                    .fillMaxSize()<br>                    .background(Color(0x88000000))<br>            ) {<br>                Box(<br>                    Modifier<br>                        .align(Alignment.TopStart)<br>                        .animateEnterExit(<br>                            enter = slideInHorizontally(),<br>                            exit = slideOutHorizontally(),<br>                            label = &quot;NotificationSlide&quot;<br>                        )<br>                        .clip(RoundedCornerShape(10.dp))<br>                        .requiredHeight(100.dp)<br>                        .fillMaxWidth()<br>                        .background(Color.White)<br>                ) {<br>                    Text(&quot;Custom Notification!&quot;, Modifier.align(Alignment.Center))<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>As the container fades in and out, our notification text slides in and out horizontally, and as you can imagine, we can stack many more animations into this make the notification execute several animations all at the native level.</p><h4>Modifier.animateItem</h4><p>If you know about LayColumn, you can imagine how it handles dynamic insertion and deletion od composables within it. Ofcourse there is a way to add animations to the insertions and deletions, and that is exactly what <strong>animateItem </strong>function does.</p><p>If you take a look at the API reference for this function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*eSoe1NWwYQWcgiRXEG_l6w.png" /></figure><p>The modifier is based within LazyItemScope which means it can only be used inside composables that expose that scope. LazyColumn and LazyRow are some examples of containers that are within LazyItemScope.</p><p>Furthermore, the three parameter that it takes is very reasonable — one for the insertion animation, one for the deletion animation and one for the time when an item is deleted and it creates a void within that container and the other composables take it’s place.</p><p>For example:</p><pre>.animateItem(<br>    fadeInSpec = tween(400),<br>    placementSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),<br>    fadeOutSpec = tween(300)<br>)</pre><p>This does a much better job than the default values, and when a deletion operation creates a void, it fills that void while making a spring dampening motion as if the ground has a spring. That looks cool in apps, many times people would use apps that have these shiny features just because it looks better.</p><p>Here is a code example for a dynamic cart where we can add or remove items in a stack and you can see the animations play out as we operate on the cart. We have added a custom modifier to reduce LoC plus it gives you, the reader, a nice little refresh about how to create custom modifiers.</p><pre>fun Modifier.customBackgroundMod(): Modifier = this<br>    .background(<br>        brush = Brush.linearGradient(<br>            colorStops = arrayOf(<br>                0.0f to Color(0xFF63FF63),<br>                0.5f to Color(0xFFFF5E5E),<br>                0.5f to Color(0xFF309BC7)<br>            ),<br>            start = Offset(0.0f, 0.0f),<br>            end = Offset(320.0f, 90.0f)<br>        ),<br>        shape = CustomRoundedRectangleShape<br>    )<br>    .padding(18.dp, 0.dp)<br>@Composable<br>fun ShoppingCartScreen() {<br>    var cartItems by remember { mutableStateOf(listOf(&quot;Apples&quot;, &quot;Bananas&quot;, &quot;Oranges&quot;)) }<br><br>    Column(Modifier.fillMaxSize().padding(16.dp)) {<br>        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {<br>            Button(onClick = {<br>                cartItems = cartItems + &quot;Item ${(cartItems.size + 1)}&quot;<br>            },<br>                colors = ButtonDefaults.buttonColors(<br>                    containerColor = Color.Transparent<br>                ),<br>                modifier = Modifier<br>                    .customBackgroundMod()) {<br>                Text(&quot;Add Item&quot;)<br>            }<br>            Button(onClick = {<br>                if (cartItems.isNotEmpty()) cartItems = cartItems.dropLast(1)<br>            },<br>                colors = ButtonDefaults.buttonColors(<br>                    containerColor = Color.Transparent<br>                ),<br>                modifier = Modifier.customBackgroundMod()) {<br>                Text(&quot;Remove Item&quot;)<br>            }<br>        }<br><br>        LazyColumn(<br>            Modifier.fillMaxSize().padding(top = 12.dp)<br>        ) {<br>            items(cartItems.size, key = { it }) { item -&gt;<br>                ListItem(<br>                    headlineContent = { Text(cartItems[item]) },<br>                    modifier = Modifier<br>                        .animateItem(<br>                            fadeInSpec = tween(400),<br>                            placementSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),<br>                            fadeOutSpec = tween(300)<br>                        )<br>                        .fillParentMaxWidth()<br>                        .padding(vertical = 6.dp)<br>                        .background(<br>                            brush = Brush.horizontalGradient(<br>                                colorStops = arrayOf(<br>                                    0.0f to Color(0xFF2446C2),<br>                                    0.5f to Color(0xFF382458),<br>                                    1.0f to Color(0xFFB51FBF)<br>                                )<br>                            ),<br>                            shape = CutCornerShape(10.dp)<br>                        )<br>                        .padding(16.dp)<br>                )<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*IgSS21uyy5NHOBS15sBlWw.gif" /></figure><p>While this covers the animation feature in modifiers, in the Android ecosystem, there are a lot many ways to animate.</p><h3>Stay tuned for more updates!</h3><p>I’ll be expanding this very article soon with deeper dives into the additional background options available in Jetpack Compose. Upcoming updates will also cover animated backgrounds and visually engaging effects to enhance your UI. If you’re interested in mastering advanced background techniques or discovering practical Compose examples, make sure to save this article to your reading list for easier access later — and check back regularly for new sections and enhancements!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d45cd26984c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Fragment Framework — Build a Responsive Master-Detail Layout using Fragments]]></title>
            <link>https://medium.com/@debasishraut.dev/android-fragment-framework-build-a-responsive-master-detail-layout-using-fragments-67eb4fb8fcbb?source=rss-5503dc1080a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/67eb4fb8fcbb</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[dynamic-layout]]></category>
            <category><![CDATA[android-layout]]></category>
            <dc:creator><![CDATA[Debasish Raut]]></dc:creator>
            <pubDate>Sat, 27 Sep 2025 10:52:19 GMT</pubDate>
            <atom:updated>2025-09-27T10:52:19.320Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Fragment Framework — Build a Responsive Master-Detail Layout using Fragments</h3><p>Fragments in android are components that exist within the lifespan of other components and they provide UI functionality that can be reused elsewhere in the app too. They have their own life cycle and are independent of the host activity events and yet we can pass data from host activity to the fragments and vice versa., which is what makes the fragments an important part of the android app architecture as it supports modularization and re-usability of components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KK0fTsPLY0er1vvjZi2XMg.png" /><figcaption>The layout converts from list to a Master Detail Layout when on larger screens. This is done using fragments.</figcaption></figure><h3>Building a Responsive Master-Detail Email App Layout with Fragments</h3><p>When designing an email app for Android, it’s important to create a user experience that adapts to different screen sizes. A <strong>Master-Detail layout</strong> is a proven pattern for this: you show a list of emails (the “master” view) and, when an email is selected, display its full content (the “detail” view).</p><h4>Why Use Fragments for Master-Detail?</h4><p>Fragments are ideal for this scenario because they allow you to modularize your UI and reuse components across different layouts. Each fragment manages its own lifecycle and logic, making it easy to swap, update, or reuse them as needed.</p><ul><li><strong>On small screens (phones):</strong> Only one fragment is visible at a time. The user sees the email list, and tapping an item navigates to the detail view.</li><li><strong>On large screens (tablets):</strong> Both fragments are shown side-by-side, allowing users to browse emails and read their content simultaneously. This makes better use of available space and improves productivity.</li></ul><h3>How to Implement our Layout with FragmentContainerView</h3><p>Android’s FragmentContainerView is the recommended way to host fragments in your XML layouts. You can define different layouts for phones and tablets by using resource qualifiers (like layout-sw600dp for tablets):</p><p><strong>Single-pane (phone):</strong></p><pre>&lt;androidx.fragment.app.FragmentContainerView<br>    android:id=&quot;@+id/fragment_container_view&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot; /&gt;</pre><p><strong>Two-pane (tablet):</strong></p><pre>&lt;LinearLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;horizontal&quot;&gt;<br>    &lt;androidx.fragment.app.FragmentContainerView<br>        android:id=&quot;@+id/email_list_container&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:layout_weight=&quot;1&quot; /&gt;<br>    &lt;androidx.fragment.app.FragmentContainerView<br>        android:id=&quot;@+id/email_detail_container&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:layout_weight=&quot;2&quot; /&gt;<br>&lt;/LinearLayout&gt;</pre><blockquote>Note: The above code is just for getting an idea about how our implementation will take shape and it is not supposed to be the actual code.</blockquote><h4>Adaptive UI with Fragments</h4><p>By using fragments and container views, you can:</p><ul><li>Dynamically add, remove, or replace fragments based on user actions or device configuration.</li><li>Share logic and UI components between different layouts, reducing code duplication.</li><li>Provide a seamless experience whether your app is running on a phone or a tablet.</li></ul><h3>Setting up the Android Studio IDE for Responsive Design development</h3><p>To start developing this, we start with a new project with empty views activity template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*MHLk225f2p-idUHVb5Pz1A.png" /></figure><p>In order to include the fragment library in our project we need to add it as a dependency as it exists in the androidx (extended) libraries. In our libs.versions.toml file add the following under their respective sections:</p><pre>[versions]<br> . . .<br>fragment_version = &quot;1.8.9&quot;<br><br>[libraries]<br> . . .<br>androidx-fragment = {group= &quot;androidx.fragment&quot;, name=&quot;fragment&quot;, version.ref = &quot;fragment_version&quot;}<br> . . .</pre><p>Next in our build.gradle module level file we can add the implementation:</p><pre>implementation(libs.androidx.fragment)</pre><p>One important step before we start working on layouts is setting up our emulators. For proper UI testing, it’s best to have both a tablet and a phone virtual device so you can preview your layouts across different screen sizes and configurations. If you have access to physical devices, definitely use them — real hardware always gives the most accurate results. But for this tutorial, we’ll stick with two emulated devices. To create a new virtual device, open Device Manager in Android Studio and click the plus button to launch the Virtual Device creation flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*BK5R99QF8LWgBkKLwyFzdA.png" /></figure><p>Under the Hardware selection window select your desired phone model to emulate, usually Pixel phones are quite good for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qG4T9gz11urIw0e6g8c8kQ.png" /></figure><p>Next select your Android API Level, you should always select the latest ones available, for this tutorial I have been using API Level 34 so I will go ahead with that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knQOaLN_g3x2FOUVFZYKpQ.png" /></figure><p>Next, do the same and add a Pixel Tablet this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_cB1mYhqxK2rAgkTGRdKw.png" /></figure><p>Make sure both your emulators are set to the same API Level for consistent testing. Once you have your tablet and phone emulators ready, you’ll want to run your app on both devices at the same time to check how your layouts behave across screen sizes. In Android Studio, look at the device selector at the top center of the IDE — this shows which device your app is currently targeting. Click the drop-down, choose ‘Select Multiple Devices,’ and check both your emulators. Now, when you hit Run, Android Studio will deploy your app to both devices simultaneously, making it easy to spot UI issues and verify your app’s responsiveness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWgeZrOrBc3nDmGszwH3gA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*ySTbJwNKaFByM-mgK5_xAA.png" /></figure><h3>Creating XML Components</h3><p>Now that our IDE is set up for responsive UI development, the first step is to create the email list item layout that will be used in our RecyclerView inside the Master Fragment’s XML. Go ahead and create a new layout resource file called master_list_item.xml in your res/layout directory. This layout will serve as the template for each email item in the list, and we&#39;ll start preparing it to display our email data—like subject, preview, and timestamp—using standard Android view components. Once this layout is ready, we can wire it up with our RecyclerView adapter and start populating the list with actual email items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*IZoOAc1LgmD0Rby-r9vOUg.png" /><figcaption>Email List Item View</figcaption></figure><p>Add the following code into master_list_item.xml:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:background=&quot;#F5F5F4&quot;&gt;<br>    &lt;TextView<br>        android:id=&quot;@+id/email_list_heading&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Heading&quot;<br>        android:textSize=&quot;24sp&quot;<br>        android:padding=&quot;12dp&quot;<br>        android:textStyle=&quot;bold&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;/&gt;<br>    &lt;TextView<br>        android:id=&quot;@+id/email_timestamp&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;09:24 am&quot;<br>        android:padding=&quot;12dp&quot;<br>        android:textColor=&quot;#1357DF&quot;<br>        android:textSize=&quot;16sp&quot;<br>        android:textStyle=&quot;bold&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;/&gt;<br>    &lt;TextView<br>        android:id=&quot;@+id/email_preview&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:textColor=&quot;#404040&quot;<br>        android:padding=&quot;12dp&quot;<br>        android:text=&quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip . . . &quot;<br>        android:textSize=&quot;16sp&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@id/email_list_heading&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;<br>    &lt;ImageView<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;1dp&quot;<br>        android:src=&quot;@drawable/separator&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@id/email_preview&quot;<br>        android:contentDescription=&quot;Separator Line&quot;<br>        android:layout_marginStart=&quot;-16dp&quot;<br>        android:layout_marginEnd=&quot;-16dp&quot;/&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>We also need a separator drawable resource for the last view in the list(the ImageView), so go ahead and create this drawable resource: <br>separator.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:shape=&quot;rectangle&quot;&gt;<br>    &lt;solid android:color=&quot;#AAAC9F&quot; /&gt;<br>&lt;/shape&gt;</pre><p>Next let’s create our Fragment Container View that will house our Master and Detail Fragments in the same screen. In the activity_main.xml we need to add the Fragment Container View like so:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;<br>    &lt;androidx.fragment.app.FragmentContainerView<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;0dp&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        app:layout_constraintHeight_percent=&quot;1&quot;<br>        android:background=&quot;#757575&quot;/&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>We should also create our detail fragment right now. Android Studio makes it easy to organize layouts for different screen sizes by using resource qualifiers when creating layout files. To do this, simply right-click on your res/layout directory and select <strong>New &gt; Layout Resource File</strong>. In the dialog, look for the <strong>Available Qualifiers</strong> section, choose <strong>Screen Width</strong>, and enter 600 to target Android tablets and larger screens. This means that whenever your app runs on a device with a screen width of 600dp or more, Android will automatically use your wide-screen layout variant.</p><p>As you might have guessed, you can also define layouts for other configurations, such as different screen orientations. For example, you could create a special layout for landscape mode by using the orientation qualifier. This flexible system lets you tailor your app’s UI to a wide range of devices and user experiences, all without extra code — Android selects the best layout at runtime based on the device’s configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*z-B4p8dewoTkXFK8Z4SsUQ.png" /></figure><p>We can now design our wide screen layout in the newly created activity_main.xml file:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;<br>    &lt;androidx.fragment.app.FragmentContainerView<br>        android:id=&quot;@+id/email_list_container&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintWidth_percent=&quot;0.3&quot;<br>        android:background=&quot;#474747&quot;<br>        /&gt;<br><br>    &lt;androidx.fragment.app.FragmentContainerView<br>        android:id=&quot;@+id/email_detail_container&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintWidth_percent=&quot;0.7&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        android:background=&quot;#A8A8A8&quot;/&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*2lYbgDc9A1fHVtokQqnNCA.png" /><figcaption>The wide screen layout contains both the fragments, as seen in our blueprint</figcaption></figure><p>There is still one more thing we need to take care of — how to detect which screen resolution we are dealing with? One effective way to easily detect whether the device is a tablet or a phone without running calculations at runtime is by utilizing Android’s resource qualifier system.</p><p>You start by creating a boolean resource file named bool.xml in your default /res/values/ directory, where you define a boolean such as isTablet and set it to false. Then, you create another bool.xml file inside /res/values-sw600dp/—a qualifier indicating screens with a minimum width of 600dp—which overrides the boolean and sets isTablet to true.</p><p>This setup allows Android’s build system to pick the correct boolean value based on the device’s screen configuration automatically. At runtime, your app can simply read the isTablet boolean resource to determine the device type without any expensive computations, making your app more efficient and your code cleaner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*RxUo-Mnk6rXJgrtxrRuXSQ.png" /><figcaption>Create a values resource file for Mobile screens</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*eoSHpIkj6LpMY2C4zf5Suw.png" /><figcaption>Create another values resource file for Table screens</figcaption></figure><h3>Wiring the Fragments</h3><p>Now that both our layouts are in place, we can start by actually creating our Master Fragment UI. If you have been keeping up with our design process you may have guessed that this fragment will hold a Recycler View and we will be using our email_list_item.xml design under this Recycler View. Create a new layout file called <strong>email_list_fragment.xml</strong> and within it type the following xml:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;ScrollView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br>    <br>    &lt;androidx.recyclerview.widget.RecyclerView<br>        android:id=&quot;@+id/email_list_recyc&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:nestedScrollingEnabled=&quot;false&quot;<br>        android:overScrollMode=&quot;never&quot; /&gt;<br>&lt;/ScrollView&gt;</pre><p>To make our RecyclerView actually display something meaningful, we need to define the data structure for our email items. This is a key step in any Android app that uses RecyclerView, since the adapter relies on a well-defined model to bind data to each list item view.</p><p>Let’s start by creating a Kotlin data class called EmailListItem under a new package named schema. This class will represent the properties of each email in our list—such as subject, preview text, timestamp, and any unique identifier we need. Defining this model up front ensures our adapter and UI code stay clean and predictable, and it makes it much easier to manage and update our data as the app grows.</p><p>Once the data class is ready, we can move on to populating our RecyclerView and wiring up the adapter to use this schema.</p><pre>package com.dev.masterdetailfragments.schema<br><br>import java.util.Date<br><br>data class EmailListItem(<br>    val oid: String,           // Unique identifier<br>    val receivedAt: Date,     // Timestamp of when the email was received<br>    val subject: String,      // Subject line of the email<br>    val preview: String       // Short preview of the email body<br>)</pre><p>Remember our sample EmailListItem layout, this data class represents the data that each of our UI component will hold — a heading(or subject), a time stamp, and a preview string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*pZvTC_ep9gG_V74JlKfO0w.png" /></figure><p>Next in our EmailDetail data class we would like to have a bit more fine grained information so let’s create a new kotlin data class and add the following code:</p><pre>package com.dev.masterdetailfragments.schema<br><br>import java.util.Date<br><br>data class EmailDetail(<br>    val oid: String,           // Same unique identifier as EmailListItem<br>    val sender: String,        // Sender&#39;s email address or name<br>    val recipient: String,     // Recipient&#39;s email address or name<br>    val sentAt: Date,          // Timestamp of when the email was sent<br>    val subject: String,       // Email subject line<br>    val bodyHtml: String       // Full HTML content of the message body<br>)</pre><p>Next let us start gathering some data. Since we will be replicating a mail box layout, let us gather some email templates. Luckily we can easily find email templates from github, there are repositories that provide email templates for marketing purposes and we shall be using these templates for our dataset. One such repository is <a href="https://github.com/ckissi/responsive-html-email-templates">Responsive HTML email Templates by ckissi</a>. This repository has folders and within each folder we have the .html files that houses the actual email. I have gathered this data and under a Kotlin object repository by creating a file EmailListData.kt under the .data package name and in here I have defined a Email Repository that mimics a real world email dataset.</p><pre>package com.dev.masterdetailfragments.data<br><br>import com.dev.masterdetailfragments.schema.EmailListItem<br>import java.util.Date<br>import java.util.GregorianCalendar<br>import java.util.concurrent.ThreadLocalRandom<br><br>object EmailRepository {<br>    fun getRandomDate(startYear: Int = 2023, endYear: Int = 2025): Date {<br>        val startMillis = GregorianCalendar(startYear, 0, 1).timeInMillis<br>        val endMillis = GregorianCalendar(endYear, 11, 31).timeInMillis<br>        val randomMillis = ThreadLocalRandom.current().nextLong(startMillis, endMillis)<br>        return Date(randomMillis)<br>    }<br><br>    fun getEmailList(): List&lt;EmailListItem&gt; = listOf(<br>        EmailListItem(&quot;e001&quot;,<br>            getRandomDate(),<br>            &quot;Please help us improve our Product&quot;,<br>            &quot;You recently canceled your {{Product}} subscription and I&#39;m sorry to see you go. Thank you for being with us. There could be various reasons for leaving and I really hope you&quot;),<br>        EmailListItem(&quot;e002&quot;,<br>            getRandomDate(),<br>            &quot;Please confirm your email&quot;,<br>            &quot;Yes, we know. An email to confirm an email. \uD83E\uDD2A Please validate your email address in order to get started using {{Product}}.  Confirm Your Email&quot;),<br>        EmailListItem(&quot;e003&quot;,<br>            getRandomDate(),<br>            &quot;Thank you for your order&quot;,<br>            &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam volutpat ut est ac dignissim. Donec pulvinar ligula metus, sed imperdiet quam pretium at. Cras finibus hendrerit magna nec euismod. Ut eget justo vel enim ultrices pharetra. Morbi tellus libero, sollicitudin pulvinar porta ac, auctor sed neque&quot;),<br>        EmailListItem(&quot;e004&quot;,<br>            getRandomDate(),<br>            &quot;It seems that you’ve forgotten your password.&quot;,<br>            &quot; If you did not make this request, just ignore this email. Otherwise please click the button above to reset your password.&quot;),<br>        EmailListItem(&quot;e005&quot;,<br>            getRandomDate(),<br>            &quot;Uh-oh! Your {{Product}} free trial just ended!&quot;,<br>            &quot;Your free trial of {{Product}} has ended, we&#39;re excited to get you started with your {{Product}} account. To give you some time to enter in your payment info we&#39;ll still collect all your data for the next 30 days.&quot;),<br>        EmailListItem(&quot;e006&quot;,<br>            getRandomDate(),<br>            &quot; Welcome to {{Product}}&quot;,<br>            &quot; Hello {{ name }}!&lt;br&gt;&lt;/br&gt;\nThank you for signing up for {{ product }}. We&#39;re really happy to have you! Click the link below to login to your account:&quot;)<br>    )<br>}</pre><p>Now what er have to do is get the html files from the repository sub-directories and store it in our resources under /res/raw folder. If you do not have raw folder by default, you can create it by right-clicking the res folder and selecting New -&gt; Android Resource Directory and then typing int the directory name as raw and the resource type also as raw.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*CrkvsFRwge245etkrxU7NA.png" /></figure><p>In this new resource directory we will store our emails in .html format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*H9h_OVha-9nFnumNLbbZoQ.png" /></figure><p>Now we shall be creating our Fragment class that we will need to replace in our main activity UI. In order to share data between fragments and to share data between the fragments and their hosts, the Fragment library provides two principal ways to carry out the transaction — using a shared ViewModel or by using the Fragment Result API. The ViewModel option allows us to persist data even when the app configurations change. Which means that when we, for instance, rotate our device, the screen orientation will change and that will trigger a recreation of the activity resulting in re-initialization of the data that was being shared. The ViewModel class is designed to withstand this recreation process and thus it is ideal for our use case. To create our ViewModel we can start by creating a class called EmailViewModel in a new models package.</p><pre>package com.dev.masterdetailfragments.models<br><br>import androidx.lifecycle.LiveData<br>import androidx.lifecycle.MutableLiveData<br>import androidx.lifecycle.ViewModel<br><br>class EmailViewModel: ViewModel() {<br>    private val mutableSelectedEmailOid = MutableLiveData&lt;String&gt;()<br>    val selectedEmailOid: LiveData&lt;String&gt; get() = mutableSelectedEmailOid<br><br>    fun selectEmail(oid: String) {<br>        mutableSelectedEmailOid.value = oid<br>    }<br>}</pre><p>This model simply stores an Object ID of an email list and we will use this Object ID to fetch the correct email in our Email Detail Fragment. The selectEmail function is responsible for updating the selected email identifier (oid) in the ViewModel&#39;s state. When this function is called with a new oid, it updates the internal MutableLiveData, which in turn notifies any observers of the selectedEmailOid LiveData.</p><p>In our EmailListFragment Layout file(email_list_fragment.xml) we have a RecyclerView which needs an adapter so we should start creating this adapter forst before we implement it in the EmailListFragment class. So let’s create a Kotlin class called EmailListAdapter. This Adapter will use the Data Class we defined earlier to represent our emails in data form. When our host activity is created, the adapter will bind our email data to the recycler view.</p><pre>package com.dev.masterdetailfragments<br><br>import android.view.LayoutInflater<br>import android.view.View<br>import android.view.ViewGroup<br>import android.widget.TextView<br>import androidx.recyclerview.widget.RecyclerView<br>import com.dev.masterdetailfragments.schema.EmailListItem<br>import java.text.SimpleDateFormat<br>import java.util.Locale<br><br>class EmailListAdapter(<br>    private val emailList: List&lt;EmailListItem&gt;,<br>    private val onClick: (String) -&gt; Unit<br>) : RecyclerView.Adapter&lt;EmailListAdapter.EmailViewHolder&gt;() {<br><br>    inner class EmailViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {<br>        val heading = itemView.findViewById&lt;TextView&gt;(R.id.email_list_heading)<br>        val preview = itemView.findViewById&lt;TextView&gt;(R.id.email_preview)<br>        val timestamp = itemView.findViewById&lt;TextView&gt;(R.id.email_timestamp)<br>    }<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EmailViewHolder {<br>        val view = LayoutInflater.from(parent.context).inflate(R.layout.master_list_item, parent, false)<br>        return EmailViewHolder(view)<br>    }<br><br>    override fun onBindViewHolder(holder: EmailViewHolder, position: Int) {<br>        val email = emailList[position]<br>        holder.heading.text = email.subject<br>        holder.preview.text = email.preview<br>        val timeFormat = SimpleDateFormat(&quot;MMM yyyy HH:mm&quot;, Locale.getDefault())<br>        holder.timestamp.text = timeFormat.format(email.receivedAt)<br>        holder.itemView.setOnClickListener {<br>            onClick(email.oid)<br>        }<br>    }<br><br>    override fun getItemCount() = emailList.size<br>}</pre><p>When an item in the RecyclerView is clicked, the adapter invokes onClick(email.oid), passing the unique identifier of the clicked email to the function provided when the adapter is constructed.</p><p>This means the adapter itself doesn’t determine what happens next — the caller decides. For example, in a fragment or activity, the developer might pass a lambda or function reference to open a detail view, update state, or communicate selection to a shared ViewModel or navigation system. The design keeps the adapter reusable and decoupled from concrete UI behaviors — very useful for handling navigation, selection, or data updates from item clicks in a clean, testable way.</p><p>Now let’s create a new Kotlin class called EmailListFragment.kt, where we&#39;ll implement our fragment using the Fragment class from the androidx.fragment.app package. This fragment will be responsible for inflating the email_list_fragment.xml layout we prepared earlier. Since this layout contains a RecyclerView, we&#39;ll set up and manage its adapter here as well. We&#39;ll also handle click events on each email list item—when an item is selected, we&#39;ll trigger the display of the corresponding EmailDetailFragment, replacing the fragment container with those details.</p><p>As you step back and view how these components fit together, you’ll notice the flexibility and organization fragments provide. By breaking the UI into modular, reusable pieces, we can set up complex interactions and responsive layouts without risking instability. This approach is at the heart of robust Android app architecture and really highlights the power of working with fragments.</p><p>Let’s go ahead and convert the words into code in the file EmailListFragment.kt:</p><pre>package com.dev.masterdetailfragments<br><br>import android.os.Bundle<br>import android.view.View<br>import androidx.fragment.app.Fragment<br>import androidx.fragment.app.activityViewModels<br>import androidx.recyclerview.widget.LinearLayoutManager<br>import androidx.recyclerview.widget.RecyclerView<br>import com.dev.masterdetailfragments.data.EmailRepository<br>import com.dev.masterdetailfragments.models.EmailViewModel<br><br>class EmailListFragment: Fragment(R.layout.email_list_fragment) {<br>    private lateinit var recyclerView: RecyclerView<br>    private lateinit var adapter: EmailListAdapter<br>    private val viewModel: EmailViewModel by activityViewModels()<br>    var onEmailSelected: ((oid: String) -&gt; Unit)? = null<br>    fun onItemClicked(oid: String) {<br>        viewModel.selectEmail(oid)<br>    }<br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br>        recyclerView = view.findViewById(R.id.email_list_recyc)<br>        recyclerView.layoutManager = LinearLayoutManager(requireContext())<br><br>        adapter = EmailListAdapter(EmailRepository.getEmailList()) { oid -&gt;<br>            onEmailSelected?.invoke(oid)<br>            onItemClicked(oid)<br>        }<br>        recyclerView.adapter = adapter<br>    }<br>}</pre><p>The EmailDetailFragment class is pretty straight forward to create now. It inflates a simple layout with some text views and a web view that is supposed to hold the actual email body in html format. So let’s create the new class EmailDetailFragment and let’s implement the Fragment class in this class:</p><pre>package com.dev.masterdetailfragments<br><br>import android.annotation.SuppressLint<br>import android.os.Bundle<br>import android.view.View<br>import android.webkit.WebView<br>import android.widget.TextView<br>import androidx.fragment.app.Fragment<br>import com.dev.masterdetailfragments.schema.EmailDetail<br>import java.util.Date<br><br>class EmailDetailFragment : Fragment(R.layout.email_detail_fragment) {<br><br>    private lateinit var senderTextView: TextView<br>    private lateinit var recipientTextView: TextView<br>    private lateinit var subjectTextView: TextView<br>    private lateinit var webView: WebView<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br>        senderTextView = view.findViewById(R.id.email_sender)<br>        recipientTextView = view.findViewById(R.id.email_recipient)<br>        subjectTextView = view.findViewById(R.id.email_subject)<br>        webView = view.findViewById(R.id.email_body_webview)<br><br>        val oid = arguments?.getString(&quot;EMAIL_OID&quot;)<br>        if (oid != null) {<br>            val emailDetail = getEmailDetailById(oid)<br>            displayEmailDetail(emailDetail)<br>        }<br>    }<br><br>    private fun getEmailDetailById(oid: String): EmailDetail {<br>        // Placeholder: Fetch or generate the email detail data here (e.g., from database or network)<br>        val emailHtmlMap = mapOf(<br>            &quot;e001&quot; to R.raw.e001,<br>            &quot;e002&quot; to R.raw.e002,<br>            &quot;e003&quot; to R.raw.e003,<br>            &quot;e004&quot; to R.raw.e004,<br>            &quot;e005&quot; to R.raw.e005,<br>            &quot;e006&quot; to R.raw.e006<br>        )<br>        val resId = emailHtmlMap[oid] ?: R.raw.e001<br>        val html = resources.openRawResource(resId).bufferedReader().use { it.readText() }<br><br>        return EmailDetail(<br>            oid = oid,<br>            sender = &quot;sender@example.com&quot;,<br>            recipient = &quot;recipient@example.com&quot;,<br>            sentAt = Date(),<br>            subject = &quot;Sample Email Subject&quot;,<br>            bodyHtml = html<br>        )<br>    }<br><br>    @SuppressLint(&quot;SetJavaScriptEnabled&quot;)<br>    private fun displayEmailDetail(emailDetail: EmailDetail) {<br>        senderTextView.text = emailDetail.sender<br>        recipientTextView.text = emailDetail.recipient<br>        subjectTextView.text = emailDetail.subject<br>        webView.loadDataWithBaseURL(null, emailDetail.bodyHtml, &quot;text/html&quot;, &quot;utf-8&quot;, null)<br>        webView.settings.javaScriptEnabled = true<br><br>    }<br>}</pre><p>When the fragment view is created, it finds the UI components by their IDs for sender, recipient, subject, and body (WebView). It then attempts to get an email identifier (EMAIL_OID) from the fragment’s arguments. If the identifier is present, it calls getEmailDetailById(oid), which reads the HTML body from the app’s resources and creates an EmailDetail object with sample email metadata. Then it passes the EmailDetail to displayEmailDetail, which sets the sender, recipient, and subject text, and loads the HTML email body into the WebView . Note that we have enabled Javascript for proper rendering of the web view. It comes with it’s own security risks so do not use it in production without creating proper checks for sanitizing the html before it reaches your app’s web view. In our tutorial, we are fairly certain that there is no risk in the htmls we are using so we can just supress the warning.</p><p>With all of this in place, the UI will adapt to mobile vs table screen sizes and show two panes in table view where as it will show one list layout in mobile view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5KS0yStH2_-lIrO-Oi_fw.png" /></figure><h3>Conclusion</h3><p>With our responsive master-detail email layout complete, you now have a solid foundation for building Android apps that adapt fluidly to phones and tablets. By leveraging fragments, shared ViewModels, and smart resource qualifiers, we’ve created a modular, scalable architecture that keeps UI logic clean and maintainable across different device configurations.</p><p>This tutorial has walked you through the core principles of fragments in Android — covering everything from layout resource management and data binding to dynamic fragment transactions. With your email list and detail views in place, you can start experimenting with richer interactions and more advanced UI components to deliver a polished, consistent experience on any screen size.</p><p>Stay tuned for upcoming tutorials where we’ll dive into the Fragment Result API for targeted fragment communication, explore multi-pane navigation patterns, and tackle even more sophisticated layout strategies. The Android Fragment framework opens the door to highly adaptive and powerful interfaces — and we’re just getting started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67eb4fb8fcbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Responsive Android Layouts :: Adaptation — Creating a responsive Word Cloud Component.]]></title>
            <link>https://medium.com/@debasishraut.dev/responsive-android-layouts-adaptation-creating-a-responsive-word-cloud-component-2e98f0df8303?source=rss-5503dc1080a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e98f0df8303</guid>
            <category><![CDATA[responsive-design]]></category>
            <category><![CDATA[flexbox]]></category>
            <category><![CDATA[word-cloud]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Debasish Raut]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 07:09:10 GMT</pubDate>
            <atom:updated>2025-09-25T07:09:10.945Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Responsive Android Layouts :: Adaptation — Creating a responsive Word Cloud Component.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SrFGDn0rzKOlLCRUChd8zQ.png" /></figure><p>Designs today need to do more than just look good — they must <em>adapt</em>. Whether it’s a phone, a billboard shifting to new size regulations, or even products changing form, the interface should stay functional and intuitive. The true mark of smart design lies in how well it preserves usability and consistency across any display or context. Flexibility isn’t optional anymore; it’s what makes design resilient and future-ready.</p><p>On Android, <strong>ConstraintLayout</strong> is the go-to tool for crafting these adaptive interfaces. By relying on flexible constraints instead of rigid positioning, it ensures your layout holds together seamlessly in every configuration. It’s the foundation for creating components that respond gracefully to change.</p><p>In this tutorial, we’ll put that into practice by building a dynamic <em>word cloud</em> — a visual representation of data that updates in real time while remaining fluid and responsive across screens.</p><h3>The Constraint Layout</h3><p>ConstraintLayout stands apart from other Android layouts by basing its design on spatial relationships, not on strict nesting. This means it’s possible to mix linear, relative, and grid-style arrangements in a single unified view — without the performance drag of deeply nested groups. The result is speedy, organized interfaces even when things get complex.</p><p>Here’s what sets ConstraintLayout apart:</p><ul><li><strong>Relative positioning</strong> lets elements be placed in relation to their parent or to other components, making it incredibly versatile.</li><li><strong>Margins</strong> control spacing between elements, even if the view is set to GONE — handy for maintaining layout structure as elements appear or vanish, using properties like layout_goneMarginStart.</li><li><strong>Centering and bias</strong> constraints act like springs, balancing views in the middle unless tweaked by a bias factor (from 0.0 to 1.0) for more nuanced placement.</li><li><strong>Circular positioning</strong> allows views to follow polar coordinates, perfect for crafting arc menus or circular layouts; think center, radius, and angle for positioning.</li><li><strong>Visibility behavior</strong> maintains margins even for invisible (GONE) views, preserving layout integrity when UI pieces frequently appear and disappear.</li><li><strong>Dimension constraints</strong> support minWidth, maxWidth, minHeight, and maxHeight for flexible sizing. It’s best to use 0dp (MATCH_CONSTRAINT) for width instead of match_parent to keep adaptive layouts predictable.</li><li><strong>Chains</strong> create orderly groups — horizontal or vertical — linked by bidirectional constraints for more controlled distribution of space.</li><li><strong>Virtual Helpers</strong> like Guidelines, Barriers, and Groups provide flexible tools for layout management without extra views cluttering the hierarchy.</li><li><strong>Optimizer</strong> streamlines common constraint patterns, skipping expensive layout passes for faster rendering in typical use cases.</li></ul><p>For a fast, responsive word cloud, Google’s Flexbox package steps in, bringing CSS-like flexibility to Android. It handles lists with varied word sizes and dynamic updates beautifully — ideal for this project.</p><p>Ready to get started? Fire up a new Android project and create an Empty Views Activity; this will be the launchpad for building out the word cloud interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*tCzGbg7JDNwYEyl7S6EN-w.png" /><figcaption>Open Android Studio and click on the New Project</figcaption></figure><p>You can name the project whatever you want, and I have named mine “WordCloud” and off we go towards the code. The first thing we need to do is to add the <a href="https://github.com/google/flexbox-layout/tree/main">Flexbox Layout</a> package. In the new Android Studio IDEs we can use a library file (.toml) to arrange our packages in a neat format and we are going to do just that. Open libs.version.toml file under Gradle Scripts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*4umb2sAwqitpxtv5d4QWMg.png" /></figure><p>Add the following changes:<br> — Under [versions] add flexboxLayout = “3.0.0” which is the version we will be using. If you have a newer version when you are reading this, make sure you are using this exact version in order to get expected results.</p><p>Under [libraries] add the following:</p><pre>flexboxLayout = { group = &quot;com.google.android.flexbox&quot;, name=&quot;flexbox&quot;, version.ref=&quot;flexboxLayout&quot;}</pre><p>We can now import the library in our actual build.gradle (Module :app) file by adding this line under dependencies:</p><pre>dependencies {<br><br>. . .<br><br>implementation(libs.flexboxLayout)<br>}</pre><p>Now let us arrange our UI to include an EditText View, a Button View to control our clicking mechanism and a RecyclerView which will hold the word cloud under a FlexboxLayout View Group. In our activity_main.xml let’s create the UI.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/main&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;com.google.android.material.textfield.TextInputEditText<br>        android:id=&quot;@+id/inputField&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:hint=&quot;Enter Anything...&quot;<br>        android:layout_margin=&quot;6dp&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toStartOf=&quot;@+id/sendButton&quot;<br>        app:layout_constraintWidth_percent=&quot;0.5&quot;/&gt;<br><br>    &lt;com.google.android.material.button.MaterialButton<br>        android:id=&quot;@+id/sendButton&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Allow&quot;<br>        android:shadowColor=&quot;@color/black&quot;<br>        android:fontFamily=&quot;sans-serif-condensed-medium&quot;<br>        android:shadowDx=&quot;4&quot;<br>        android:shadowDy=&quot;4&quot;<br>        android:shadowRadius=&quot;8&quot;<br>        android:textColor=&quot;@color/white&quot;<br>        android:textSize=&quot;24sp&quot;<br>        android:textStyle=&quot;bold&quot;<br>        android:letterSpacing=&quot;0.1&quot;<br>        app:backgroundTint=&quot;@null&quot;<br>        android:background=&quot;@drawable/tabl_btn&quot;<br>        android:layout_margin=&quot;2dp&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toEndOf=&quot;@+id/inputField&quot;<br>        app:layout_constraintWidth_percent=&quot;0.4&quot;/&gt;<br>    &lt;androidx.recyclerview.widget.RecyclerView<br>        android:id=&quot;@+id/word_cloud&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        app:layout_constraintBottom_toTopOf=&quot;@id/inputField&quot;/&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>Next we should set up the Recycler view. The Recycler View will contain the word bubbles and we will supply our Activity with a Linked hash map of a word frequency table.</p><pre>class MainActivity : AppCompatActivity() {<br><br>    private lateinit var wordCloud: RecyclerView<br>    private lateinit var sendBtn: Button<br>    private lateinit var textInput: EditText<br>    private lateinit var wordCloudAdapter: WordCloudAdapter<br><br>    private val wordCloudData: LinkedHashMap&lt;String, Int&gt; = linkedMapOf(<br>        &quot;apple&quot; to 12,<br>        &quot;banana&quot; to 27,<br>        &quot;cherry&quot; to 87,<br>        &quot;date&quot; to 24,<br>        &quot;elden berry&quot; to 56<br>    )<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        wordCloud = findViewById(R.id.word_cloud)<br>        sendBtn = findViewById(R.id.sendButton)<br>        textInput = findViewById(R.id.inputField)<br><br>        setupRecyclerView()<br>        setupSendButton()<br>    }<br><br>    private fun setupRecyclerView() {<br>        val layoutManager = FlexboxLayoutManager(this).apply {<br>            flexDirection = FlexDirection.ROW<br>            justifyContent = JustifyContent.SPACE_EVENLY<br>        }<br>        wordCloud.layoutManager = layoutManager<br>        wordCloudAdapter = WordCloudAdapter(wordCloudData)<br>        wordCloud.adapter = wordCloudAdapter<br>    }<br><br>    private fun setupSendButton() {<br>        sendBtn.setOnClickListener {<br>            val text = textInput.text.toString().trim().lowercase()<br>            if (text.isNotEmpty()) {<br>                wordCloudAdapter.addWord(text)<br>            }<br>        }<br>    }<br>}</pre><p>Here we have created a dummy data called wordCloudData and we have set up our views and buttons accordingly. Currently any new text is added to the frequency data(wordCloudData) using the addWord function.</p><p>For our RecyclerView adapter, we will have to create a Kotlin class called WordCloudAdapter:</p><pre>package com.dev.wordcloud<br><br>import android.view.LayoutInflater<br>import android.view.View<br>import android.view.ViewGroup<br>import android.widget.TextView<br>import androidx.recyclerview.widget.RecyclerView<br><br>class WordCloudAdapter(private val wordCloud: LinkedHashMap&lt;String, Int&gt;) :<br>    RecyclerView.Adapter&lt;WordCloudAdapter.ViewHolder&gt;() {<br><br>    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {<br>        val wordText: TextView = itemView.findViewById(R.id.word)<br>    }<br><br>    private val minSize = 12f<br>    private val maxSize = 32f<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {<br>        val view = LayoutInflater.from(parent.context)<br>            .inflate(R.layout.word, parent, false)<br>        return ViewHolder(view)<br>    }<br><br>    override fun onBindViewHolder(holder: ViewHolder, position: Int) {<br>        val entry = wordCloud.entries.elementAt(position)<br>        holder.wordText.text = entry.key<br>        holder.wordText.textSize = getScaledTextSize(entry.value)<br>    }<br><br>    override fun getItemCount(): Int = wordCloud.size<br><br>    fun addWord(word: String) {<br>        if (wordCloud.containsKey(word)) {<br>            val index = wordCloud.keys.indexOf(word)<br>            wordCloud[word] = wordCloud.getOrDefault(word, 0) + 1<br>            notifyItemChanged(index)<br>        } else {<br>            wordCloud[word] = 1<br>            notifyItemInserted(wordCloud.size - 1)<br>        }<br>    }<br><br>    private fun getScaledTextSize(frequency: Int): Float {<br>        val max = wordCloud.values.maxOrNull() ?: 0<br>        val min = wordCloud.values.minOrNull() ?: 0<br><br>        return if (max == min) {<br>            (minSize + maxSize) / 2f<br>        } else {<br>            minSize + (frequency - min) * (maxSize - minSize) / (max - min).toFloat()<br>        }<br>    }<br>}</pre><p>RecyclerView’s adapter isn’t just the bridge between XML layout and app logic; it’s the command center for all calculations tied to how list items should look and behave. When building a word cloud, it’s here that word frequency is converted into visual impact. If text size is pegged directly to frequency, words with the highest counts can balloon out of proportion, crowding out the rest. That’s why it’s essential to scale these sizes for a neat display.</p><p>By applying a MinMax scaler within the function getScaledTextSize, the adapter normalizes frequencies. This ensures words at the mode frequency hit a preset maximum, while others shrink proportionally. This results in a crisp, balanced word cloud that looks just as good as it functions, no matter how the dataset shifts.</p><p>The main word cloud component is now set — dynamic, clear, and visually structured, with the RecyclerView adapter handling the choreography between data and design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*oGKgm8UjNYuLqzsxudLZYA.png" /><figcaption>Word Cloud builder that takes in keyboard input and puts them on a frequency table visualization.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e98f0df8303" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Responsive Android Layouts: The Basics]]></title>
            <link>https://medium.com/@debasishraut.dev/responsive-android-layouts-the-basics-9d68e6615b95?source=rss-5503dc1080a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d68e6615b95</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-ui]]></category>
            <category><![CDATA[android-layout]]></category>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[ui-ux-design]]></category>
            <dc:creator><![CDATA[Debasish Raut]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 06:30:43 GMT</pubDate>
            <atom:updated>2025-09-15T06:30:43.843Z</atom:updated>
            <content:encoded><![CDATA[<h3>Responsive Android Layouts: Choosing the Right Structure for Any App :: The Basics</h3><p>Any UI developer starts their development process by creating the <strong>layouts </strong>where the various UI components will be placed. Layout design in itself is an important part of the process because this is where a lot of crucial parts of the design lays its foundation, and a bad layout design can break the app very fast when it encounters a weird screen size in the wild. <strong>Responsiveness App Design</strong> is an inherent solution in layout design and if not handled properly can lead to disastrous outcomes if deployed to production. In this article, we’ll explore the fundamental Android layout types and provide a comprehensive comparison of their performance, usability, organizational clarity, and ideal use cases.</p><h3><strong>At the Atomic Level …</strong></h3><p>Before exploring advanced layouts, it’s important to begin with the atomic unit of any Android UI - the <strong>View</strong> class. The View class forms the foundation of all UI components in Android and represents a rectangular area on the screen responsible for drawing content and handling user interactions. Every UI element, from simple buttons and text fields to complex custom widgets, directly or indirectly inherits from this base View class. Understanding its properties and behaviors is crucial because all layouts ultimately manage collections of Views arranged in various ways to create the interface.</p><p>Simply put, the View class represents a rectangular area on the screen responsible for drawing content and handling user events within that area. When the View’s onDraw() method is called, it receives a Canvas object, and developers use various Canvas methods to draw within the rectangular area that the View occupies. The Canvas provides APIs for drawing primitives like lines, rectangles, circles, paths, or bitmaps, as well as applying transformations or clipping areas. All views in an Android window are organized into a single <strong>hierarchical tree</strong>, which can be constructed either programmatically in code or defined declaratively through one or more XML layout files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HiB3kYicoTsyKq0fmBTv1A.png" /><figcaption><strong>Figure 1.</strong> Illustration of a view hierarchy, which defines a UI layout. (source: <a href="https://developer.android.com/develop/ui/views/layout/declaring-layout">https://developer.android.com/develop/ui/views/layout/declaring-layout</a>)</figcaption></figure><p>Once a view hierarchy is established, there are several common functionalities that UI developers frequently use:</p><ul><li><strong>Set properties:</strong> Modify the attributes of a view using built-in setter methods.</li><li><strong>Manage focus:</strong> A view usually calls requestFocus() to gain active status before handling user interactions.</li><li><strong>Attach listeners:</strong> Event listeners enable dynamic behavior by responding to user actions. For example, setOnFocusChangeListener() detects focus changes, while specific subclasses like Button provide click listeners.</li><li><strong>Control visibility:</strong> Views can be shown or hidden programmatically using setVisibility(), allowing dynamic UI updates.</li></ul><p>These operations form the core toolkit for managing views and creating interactive, responsive user interfaces.</p><h4><strong>Common View Attributes</strong></h4><p>Every View and ViewGroup supports various XML attributes that define their appearance and behavior. Some attributes are unique to specific views — like textSize for TextView—while others, such as id, come from the base View class and apply to all views. Layout parameters are special attributes that describe how a view should be positioned and sized relative to its parent ViewGroup.</p><h4><strong>ID Attribute</strong></h4><p>The id attribute assigns a unique identifier to a view within the hierarchy. Defined in XML like this:</p><pre>android:id=&quot;@+id/my_button&quot;</pre><p>The id attribute can then be used in code to reference the specific view. the @ symbol indicates a resource reference, and the + means this ID will be <strong>created </strong>as a new resource in your app&#39;s <strong>R.java</strong> file. Proper use of IDs is essential to reference and manipulate views programmatically.</p><h4>Layout Position</h4><p>A view is defined by a rectangular area with a position and size. Its location is expressed by the left (x) and top (y) coordinates relative to its parent, measured in pixels. You can get these values using getLeft() and getTop(). For example, if getLeft() returns 20, the view is positioned 20 pixels to the right of its parent’s left edge.</p><p>Convenience methods like getRight() and getBottom() return the coordinates of the right and bottom edges of the view’s rectangle. For instance, getRight() is equivalent to getLeft() + getWidth().</p><h4>Size, Padding, and Margins</h4><p>A view’s size is defined by its width and height, which come in two forms: <strong>measured</strong> and <strong>actual</strong>. The measured width and height represent how big a view wants to be within its parent and can be accessed via getMeasuredWidth() and getMeasuredHeight(). The actual width and height indicate the size the view occupies on screen after layout, available through getWidth() and getHeight(). These values are not always the same and must be treated as such.</p><p>Padding specifies the space inside the view’s edges, offsetting its content. It is set in pixels for the left, top, right, and bottom sides using methods like setPadding() and can be queried with getPaddingLeft(), getPaddingTop(), etc.</p><p>While views support padding, <strong>margins</strong> — the space outside a view — are managed by the ViewGroup’s layout parameters, not the view itself.</p><h4>Dimension Units in Android</h4><p>In Android XML, dimensions are numbers followed by units, such as 10px, 5dp, or 12sp. These units define the size or spacing of UI elements and help ensure consistent display across devices.</p><p>Common units include:</p><ul><li><strong>dp (Density-independent Pixels):</strong> An abstract unit based on screen density (160 dpi baseline). 1dp roughly equals 1 pixel on a 160 dpi screen. Using dp ensures UI elements keep consistent physical size across different screen densities.</li><li><strong>sp (Scale-independent Pixels):</strong> Similar to dp but also scaled by the user’s font size preference. Recommended for font sizes to respect user accessibility settings.</li><li><strong>px (Pixels):</strong> Actual pixels on the screen. Using px is discouraged because pixel density varies across devices, leading to inconsistent sizing.</li><li><strong>pt (Points):</strong> 1/72 of an inch based on physical screen size.</li><li><strong>mm (Millimeters):</strong> Physical unit based on screen size.</li><li><strong>in (Inches):</strong> Physical size based on inches.</li></ul><p>Using <strong>dp</strong> and <strong>sp</strong> units over px helps achieve a responsive and accessible UI across varied Android devices.</p><h4>Security: Touch Filtering with setFilterTouchesWhenObscured</h4><p>To prevent malicious apps from tricking users into tapping hidden or obscured views — known as <strong>tapjacking</strong> — Android provides a <strong>touch filtering mechanism</strong>. When enabled by calling setFilterTouchesWhenObscured(true) or setting the XML attribute android:filterTouchesWhenObscured=&quot;true&quot;, the system discards touch events on views that are obscured by another visible window (like a toast, dialog, or overlay) at the touch location.</p><p>This feature ensures that sensitive actions — such as granting permissions or making purchases — can only be performed when the user clearly interacts with the intended UI, protecting against spoofing attacks where malicious overlays intercept or hijack user input.</p><h3><strong>Overview of Core Android Layout Types</strong></h3><blockquote><strong><em>Note:</em></strong><em> Although you can nest one or more layouts within another layout to achieve your UI design, keep your </em><strong><em>layout hierarchy</em></strong><em> as </em><strong><em>shallow </em></strong><em>as possible. Your layout draws faster if it has fewer nested layouts. A wide view hierarchy is better than a deep view hierarchy.</em></blockquote><h3>LinearLayout</h3><p>LinearLayout arranges child views in a single <strong>vertical or horizontal</strong> row and creates a scrollbar if the length of the window exceeds the length of the screen.</p><p>Key attributes:</p><ul><li>android:orientation (&quot;vertical&quot; or &quot;horizontal&quot;)</li><li>android:layout_weight (for proportional sizing)</li><li>android:gravity (alignment inside the layout)</li><li>android:layout_gravity (alignment of the view itself)</li></ul><p>Example:</p><pre>&lt;LinearLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:gravity=&quot;center&quot;&gt;<br>&lt;TextView<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Hello&quot;/&gt;<br>    &lt;Button<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_weight=&quot;1&quot;<br>        android:text=&quot;Click Me&quot;/&gt;<br>&lt;/LinearLayout&gt;</pre><h3>RelativeLayout</h3><p>RelativeLayout arranges children relative to each other or the parent.</p><p>Key attributes:</p><ul><li>android:layout_alignParentTop, android:layout_alignParentBottom, android:layout_alignParentStart, android:layout_alignParentEnd</li><li>android:layout_toRightOf, android:layout_below, android:layout_above, android:layout_toLeftOf</li><li>android:layout_centerInParent, android:layout_centerHorizontal, android:layout_centerVertical</li></ul><p>Example:</p><pre>&lt;RelativeLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;&gt;<br>&lt;TextView<br>        android:id=&quot;@+id/text1&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Text 1&quot;<br>        android:layout_alignParentStart=&quot;true&quot;/&gt;<br>    &lt;Button<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Button&quot;<br>        android:layout_toEndOf=&quot;@id/text1&quot;<br>        android:layout_marginStart=&quot;16dp&quot;/&gt;<br>&lt;/RelativeLayout&gt;</pre><h3>FrameLayout</h3><p>FrameLayout displays a single child or stacks children.</p><p>Key attributes:</p><ul><li>android:layout_gravity (controls child&#39;s position inside the FrameLayout)</li></ul><p>Example:</p><pre>&lt;FrameLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br>&lt;ImageView<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:src=&quot;@drawable/background&quot;/&gt;<br>    &lt;TextView<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        android:text=&quot;Overlay Text&quot;/&gt;<br>&lt;/FrameLayout&gt;</pre><h3>ConstraintLayout</h3><p>ConstraintLayout enables complex UI positioning with flat hierarchies.</p><p>Key attributes:</p><ul><li>app:layout_constraintTop_toTopOf, app:layout_constraintBottom_toBottomOf</li><li>app:layout_constraintStart_toStartOf, app:layout_constraintEnd_toEndOf</li><li>app:layout_constraintHorizontal_bias, app:layout_constraintVertical_bias</li><li>app:layout_constraintHeight_default (e.g., &quot;wrap&quot;, &quot;spread&quot;, &quot;percent&quot;)</li></ul><p>Example:</p><pre>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br>&lt;Button<br>        android:id=&quot;@+id/button&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Constrained Button&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        app:layout_constraintHorizontal_bias=&quot;0.5&quot;/&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><h3>GridLayout</h3><p>GridLayout arranges children in a grid with configurable rows and columns.</p><p>Key attributes:</p><ul><li>android:rowCount, android:columnCount</li><li>android:layout_row, android:layout_column (for child positioning)</li><li>android:layout_rowSpan, android:layout_columnSpan</li></ul><p>Example:</p><pre>&lt;GridLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:rowCount=&quot;2&quot;<br>    android:columnCount=&quot;2&quot;&gt;<br>&lt;Button<br>        android:layout_row=&quot;0&quot;<br>        android:layout_column=&quot;0&quot;<br>        android:text=&quot;Button 1&quot;/&gt;<br>    &lt;Button<br>        android:layout_row=&quot;0&quot;<br>        android:layout_column=&quot;1&quot;<br>        android:text=&quot;Button 2&quot;/&gt;<br>    &lt;Button<br>        android:layout_row=&quot;1&quot;<br>        android:layout_column=&quot;0&quot;<br>        android:layout_columnSpan=&quot;2&quot;<br>        android:text=&quot;Button 3&quot;/&gt;<br>&lt;/GridLayout&gt;</pre><h3>TableLayout</h3><p>TableLayout arranges elements into rows and columns similarly to an HTML table.</p><p>Key attributes:</p><ul><li>TableRow to define rows</li><li>Child views inside TableRow representing columns</li></ul><p>Example:</p><pre>&lt;TableLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;&gt;<br>&lt;TableRow&gt;<br>        &lt;TextView android:text=&quot;Name&quot;/&gt;<br>        &lt;TextView android:text=&quot;Age&quot;/&gt;<br>    &lt;/TableRow&gt;<br>    &lt;TableRow&gt;<br>        &lt;TextView android:text=&quot;John&quot;/&gt;<br>        &lt;TextView android:text=&quot;25&quot;/&gt;<br>    &lt;/TableRow&gt;<br>    &lt;TableRow&gt;<br>        &lt;TextView android:text=&quot;Jane&quot;/&gt;<br>        &lt;TextView android:text=&quot;30&quot;/&gt;<br>    &lt;/TableRow&gt;<br>&lt;/TableLayout&gt;</pre><h3>Conclusion</h3><p>Designing responsive Android layouts is both an art and a science, involving thoughtful choices to balance performance, usability, and maintainability. From understanding the fundamentals of Views and their hierarchy to mastering core layout types like LinearLayout, RelativeLayout, and ConstraintLayout, each decision shapes the user experience across diverse devices.</p><p>If this exploration has piqued your curiosity, there is much more to uncover — optimizing layout performance, exploring advanced layouts like MotionLayout, or even diving into Jetpack Compose’s declarative UI approach.</p><p>Feel free to reach out if you have any questions, suggestions, or corrections. Your feedback helps refine these insights and drives deeper discussions. You can connect with me via mail at debasishraut.dev@gmail.com, or ping me on <a href="https://www.linkedin.com/in/debasish-raut-8267ab165/">LinkedIn</a>.</p><p>Keep experimenting and pushing the boundaries of responsive design!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d68e6615b95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Android UI Design with XML]]></title>
            <link>https://medium.com/@debasishraut.dev/introduction-to-android-ui-design-with-xml-b777e09c8d10?source=rss-5503dc1080a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b777e09c8d10</guid>
            <category><![CDATA[android-xml]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[android-ui]]></category>
            <dc:creator><![CDATA[Debasish Raut]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 09:20:20 GMT</pubDate>
            <atom:updated>2025-09-12T09:20:20.896Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why do we need XML in Android Development?</strong></p><p>UI (User Interface) plays an important role in an app. It creates a first impression for users, which eventually leads to more engagement. Android provides some cool built-in components to create a simple yet elegant UI, but sometimes to make a product easier and more engaging, we might need to pick it up a notch. Custom views are the most important and interesting for building UI components.</p><p>In Android development, XML (Extensible Markup Language) plays a crucial role in defining the user interface (UI) of an application. It allows developers to describe the layout, structure, and appearance of UI components in a clear, structured, and human-readable format separate from the application’s logic code. Although newer declarative UI frameworks like Jetpack Compose are gaining popularity, XML remains the backbone for defining layouts in many Android apps due to its maturity, tooling support, and compatibility with existing codebases.</p><h3>Understanding XML Tags and Structures</h3><p>The simplest XML tag is :</p><pre>&lt;tag_name&gt;Hello World!&lt;/tag_name&gt;</pre><p>In regular XML, there is no restriction on tag names. You can define and use any tag as long as the document is well-formed and has a <strong>single </strong>root:</p><pre>&lt;bookstore&gt;<br>  &lt;book&gt;<br>    &lt;title&gt;Learning XML&lt;/title&gt;<br>    &lt;author&gt;Alan&lt;/author&gt;<br>  &lt;/book&gt;<br>  &lt;magazine&gt;<br>    &lt;title&gt;XML Monthly&lt;/title&gt;<br>  &lt;/magazine&gt;<br>&lt;/bookstore&gt;</pre><p>In Android, XML is used to implement UI-related data. The User Interface for an Android App is built as a hierarchy of main layouts and widgets. The layouts are ViewGroup objects or containers that control how the child view should be positioned on the screen. Widgets here are View objects, such as Buttons and TextViews.</p><p>Android’s own defined XML tags and attributes (like &lt;LinearLayout&gt;, &lt;TextView&gt;, and android:layout_width) are identified and managed through the Android XML namespace, specified as:</p><pre>xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</pre><p>In Android XML files, the <strong>tools namespace</strong> is a special namespace used primarily for design-time attributes that help with previewing and editing layouts in Android Studio but have <strong>no effect at runtime</strong>.</p><p>Typically declared in the root element of an XML layout like this:</p><pre>xmlns:tools=&quot;http://schemas.android.com/tools&quot;</pre><p>This tools namespace is part of Android’s resource tooling system and is recognized only by the IDE and build tools, making it a purely design-time aid.</p><h3>XML Parsing in Android</h3><p>Android has three types of XML parsers to parse XML data in applications:</p><ul><li><strong>DOM Parser</strong></li><li><strong>SAX Parser</strong></li><li><strong>XMLPullParser</strong></li></ul><p>Think of these parsers as highly efficient tools that process XML tags like a knife cutting butter. XML’s support for hierarchical structures is one of its core strengths, making it especially suitable for defining Android UI and complex data components.</p><p><strong>What is a View?</strong></p><p>A <strong>View</strong> is the most basic element for building a UI component. It represents an area on the screen that can provide different click events, display widgets (like buttons, TextViews), and more.</p><p><strong>What is a ViewGroup?</strong></p><p>A <strong>ViewGroup</strong> is a subclass of View. It can hold multiple views which eventually build up the UI. It is the base class for all layouts (containers holding ViewGroup or View objects).</p><p><strong>How does Android draw views?</strong></p><p>When an Activity comes to the foreground, it finds or asks for the <strong>root view</strong> — the top parent layout in its hierarchy. Then it starts drawing the entire hierarchy: the parent first, followed by children (and any sub-hierarchy they contain), recursively.</p><p><strong>The View Class in detail</strong></p><p>At the atomic level of Android UI, the View class is the basic building block for user interface components. A View occupies a rectangular area on the screen and handles drawing and event handling. View is the base class for widgets used to create interactive components (buttons, text fields, etc.).</p><p>The ViewGroup subclass is the base class for layouts, which are invisible containers that hold other Views (or other ViewGroups) and define their layout properties. All views in a window are arranged in a single tree. You can add views either programmatically or by specifying a tree of views in one or more XML layout files.</p><p>When adding a view component programmatically in Android, where that component attaches itself depends on the <strong>parent ViewGroup</strong> you specify in your code. The Android UI is organized as a single hierarchical tree of views rooted at a top-level container (usually set by setContentView()), and every view either is a root or nested inside a parent view group.</p><h3>What is Inflating?</h3><p>In Android, <em>inflating</em> refers to the process of turning an XML layout file into corresponding View and ViewGroup objects in memory at runtime.</p><p>Example:</p><pre>val view = LayoutInflater.from(context)<br>            .inflate(R.layout.my_layout, parent, false)</pre><p>Android parses my_layout.xml, creates all the view objects described inside, and returns the root View object so you can use it in your code.</p><h3>Android View Class: Key Attributes and Methods</h3><ul><li><strong>Creation &amp; Initialization:</strong><br> Views are created either programmatically or inflated from XML layouts. They have constructors that take a Context and optionally an AttributeSet for XML attributes. Once all child views are inflated, onFinishInflate() is called.</li><li><strong>Measurement &amp; Layout:</strong><br> Views participate in a two-pass layout process:</li><li>onMeasure(int widthMeasureSpec, int heightMeasureSpec) is called to determine each view’s desired size within parent constraints.</li><li>onLayout(boolean changed, int left, int top, int right, int bottom) sets the final size and position of the view and its children.<br> Measured dimensions (getMeasuredWidth()/getMeasuredHeight()) are what the view <em>wants</em> while width/height (getWidth()/getHeight()) are actual rendered sizes.</li><li><strong>Positioning:</strong><br> View positioning is relative to its parent using getLeft(), getTop(), getRight(), and getBottom(). These define the bounding rectangle of the view on screen.</li><li><strong>Padding &amp; Margins:</strong><br> Padding adds space inside the view’s boundaries, pushing content inward (using setPadding()/getPadding...() methods). Margins provide space outside the view, managed by the parent layout via ViewGroup.MarginLayoutParams.</li><li><strong>Drawing:</strong><br> Views draw themselves in onDraw(Canvas canvas). Drawing happens back-to-front in the view hierarchy, with parents drawn before children. Call invalidate() to request a redraw.</li><li><strong>Event Handling:</strong><br> Views handle input events like touches (onTouchEvent()), key events (onKeyDown()/onKeyUp()), trackball, hover, and generic motion events. Views respond by overriding these methods.</li><li><strong>Focus:</strong><br> Views gain or lose keyboard or input focus with onFocusChanged() and onWindowFocusChanged(). Focusability is controlled via setFocusable(boolean) and setFocusableInTouchMode(boolean).</li><li><strong>Attachment &amp; Visibility:</strong><br> Lifecycle methods onAttachedToWindow() and onDetachedFromWindow() notify when views are added to or removed from a window. onWindowVisibilityChanged() tracks changes in window visibility.</li><li><strong>IDs &amp; Tags:</strong><br> Views often have IDs assigned in XML for reference (via findViewById()), which should be unique within a relevant subtree. Tags (setTag()) provide a way to attach arbitrary data to a view.</li><li><strong>Themes:</strong><br> Views inherit style attributes from the Context’s theme. A different theme can be applied using the android:theme attribute or a ContextThemeWrapper.</li><li><strong>Animation Support:</strong><br> Views have properties like alpha and translationX/Y for animating appearance and position. Animations can be set with the animator framework or legacy animation classes.</li><li><strong>Scrolling Support:</strong><br> Views maintain scroll positions and support scrollbars with methods like scrollBy(), scrollTo(), and awakenScrollBars().</li><li><strong>Touch Mode &amp; Accessibility:</strong><br> Views respect touch mode behavior that changes focus behavior based on input type (keyboard vs touch).</li></ul><h3>Types of Views in Android</h3><p>Android Views can be categorized broadly as:</p><ul><li><strong>Basic Widgets:</strong> Simple elements for display or input<br> Examples: TextView, ImageView, Button, EditText, CheckBox</li><li><strong>ViewGroups (Layouts):</strong> Containers that organize child views<br> Examples: LinearLayout, RelativeLayout, ConstraintLayout, FrameLayout, ScrollView</li><li><strong>Specialized Views:</strong> For displaying web content, video, maps, etc.<br> Examples: WebView, SurfaceView, TextureView, MapView</li><li><strong>Custom Views:</strong> User-defined classes extending View or ViewGroup to implement special UI components.</li></ul><h3>LinearLayout</h3><h4>Introduction</h4><p>LinearLayout is a simple and commonly used ViewGroup that arranges its child views in a <strong>single row (horizontal)</strong> or <strong>column (vertical)</strong>. It’s ideal for stacking views sequentially in one direction.</p><h4>Example Code</h4><pre>&lt;LinearLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:padding=&quot;16dp&quot;&gt;<br>&lt;TextView<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Name:&quot; /&gt;<br>    &lt;EditText<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot; /&gt;<br>    &lt;Button<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Submit&quot; /&gt;<br>&lt;/LinearLayout&gt;</pre><h4>Layout Structure</h4><ul><li>Children are stacked vertically or horizontally.</li><li>You can nest LinearLayouts within each other to create complex UIs but beware of performance overhead due to deep hierarchies.</li></ul><h4>Important Attributes</h4><p>android:orientation : Direction of stacking: &quot;vertical&quot; (default) or &quot;horizontal&quot; .</p><p>android:weightSum : Defines how much space a child should occupy relative to siblings.</p><p>android:gravity : Controls the alignment of children inside the layout.</p><p>android:layout_gravity : Controls how individual children are positioned inside the layout.</p><h3>RelativeLayout</h3><h4>Introduction</h4><p>RelativeLayout is a ViewGroup that organizes children <strong>relative to each other or the parent container</strong>. It offers flexible positioning without deep nesting, ideal for complex UIs.</p><h4>Example Code</h4><pre>&lt;RelativeLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:padding=&quot;16dp&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/labelName&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Name:&quot; /&gt;<br><br>    &lt;EditText<br>        android:id=&quot;@+id/editName&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_toRightOf=&quot;@id/labelName&quot;<br>        android:layout_alignBaseline=&quot;@id/labelName&quot; /&gt;<br><br>    &lt;Button<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Submit&quot;<br>        android:layout_below=&quot;@id/editName&quot;<br>        android:layout_centerHorizontal=&quot;true&quot; /&gt;<br>&lt;/RelativeLayout&gt;</pre><h4>Important Attributes</h4><p>android:layout_alignParentTop : Align child to top of parent<br>android:layout_alignParentBottom : Align child to bottom of parent<br>android:layout_alignParentLeft : Align child to left of parent<br>android:layout_alignParentRight : Align child to right of parent<br>android:layout_below : Position below another view (use view’s id)<br>android:layout_above : Position above another view<br>android:layout_toLeftOf : Position left of another view<br>android:layout_toRightOf : Position right of another view<br>android:layout_centerInParent : Center child entirely<br>android:layout_centerHorizontal : Center child horizontally<br>android:layout_centerVertical : Center child vertically</p><h4>Example Code: Adding a Simple Layout with Button and TextView</h4><pre>&lt;!-- res/layout/activity_main.xml --&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot; android:padding=&quot;16dp&quot;&gt;<br>&lt;TextView<br>        android:id=&quot;@+id/tvWelcome&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Welcome to Android UI!&quot;<br>        android:textSize=&quot;20sp&quot; /&gt;<br>    &lt;Button<br>        android:id=&quot;@+id/btnClickMe&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Click me&quot; /&gt;<br>&lt;/LinearLayout&gt;</pre><p>And in Activity:</p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    setContentView(R.layout.activity_main)<br>    val button = findViewById&lt;Button&gt;(R.id.btnClickMe)<br>    val textView = findViewById&lt;TextView&gt;(R.id.tvWelcome)<br>    button.setOnClickListener {<br>        textView.text = &quot;Button clicked!&quot;<br>    }<br>}</pre><h3>Challenge for Students</h3><p><strong>Create a custom clock UI for a binary clock.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*cbO1bHMsA3twe0-ZfP1EXQ.png" /></figure><p>A binary clock displays the time using a series of dots, where each dot represents a binary digit (bit). The dots “light up” (change appearance) to represent hours, minutes, and seconds in binary form.</p><p>Your task is to:</p><ul><li>Build a custom layout view component that arranges multiple ImageView components representing the dots.</li><li>Each dot should visually indicate ON (lit) or OFF (unlit) states.</li><li>The clock should dynamically update every second to reflect the current time in binary.</li><li>You can implement this by extending a ViewGroup or combining layout managers with child views.</li><li>Bonus: Allow customization of dot sizes, colors for ON/OFF states, and spacing between dots via XML attributes.</li></ul><p>This project will help you explore custom views, layouts, UI updating with timers, and event handling in Android.</p><p><em>Hints: Research how to create a custom view by extending </em><em>ViewGroup, define custom XML attributes with </em><em>&lt;declare-styleable&gt;, and handle attribute parsing in constructors.</em></p><p>This challenge encourages exploration of custom view creation, attribute management, and view lifecycle methods, while still manageable for motivated beginners.</p><h3>Conclusion</h3><p>XML remains a fundamental part of Android UI development due to its structured way to define layouts, separation from logic code, and mature tooling support. Understanding Views and ViewGroups as the building blocks of the UI hierarchy is essential for mastering Android UI design. While Jetpack Compose is advancing UI development with a modern declarative approach, knowledge of XML and classic view management remains vital for legacy and complex applications.</p><p>By mastering XML layouts, view lifecycles, and custom views, developers can create flexible, efficient, and engaging user interfaces. Exploring custom view creation and layout management prepares one well for more advanced UI tasks and new Android UI toolkits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b777e09c8d10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[House Price Prediction with California Housing Dataset: Data Exploration, Spatial Modeling, and…]]></title>
            <link>https://medium.com/@debasishraut.dev/house-price-prediction-with-california-housing-dataset-data-exploration-spatial-modeling-and-f23202bba8ee?source=rss-5503dc1080a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f23202bba8ee</guid>
            <category><![CDATA[universityassignmnethelp]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[gwr]]></category>
            <category><![CDATA[geospatial-analytics]]></category>
            <category><![CDATA[machinelearningassignment]]></category>
            <dc:creator><![CDATA[Debasish Raut]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 09:33:54 GMT</pubDate>
            <atom:updated>2025-08-29T07:56:37.250Z</atom:updated>
            <content:encoded><![CDATA[<h3>House Price Prediction with California Housing Dataset: Data Exploration, Spatial Modeling, and Investment Insights</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l74UASTUGLVqCwAsbVP6JA.png" /></figure><h3><strong>Introduction</strong></h3><p>Step-by-step house price prediction project using the California Housing dataset. Ideal machine learning and data science project guide for university students — includes data preprocessing, model training, and performance evaluation.</p><p>The California Housing dataset is a widely used dataset for regression and predictive modeling tasks, especially in machine learning. If your university still asks you to use the <strong>Boston Housing dataset</strong> (via load_boston), just know that it was actually <strong>deprecated and removed</strong> because of ethical concerns. The dataset included features that essentially segregated people based on skin color, and while data at that time showed that certain communities with darker skin were more likely to be impoverished, that was tied to a very narrow time frame. It’s not a universal or timeless pattern, and treating it as such is simply misleading. Honestly, it should’ve been retired way earlier—using race as a predictor for housing prices is a clear case of false causality and goes against everything that data science stands for.</p><p>Anyways, back to the California housing dataset — it can be easily loaded using scikit-learn’s fetch_california_housing function and is free of missing values, providing a clean foundation for experimentation and learning.</p><p>Column Description:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b13d3981395b2e3dcd2a137b1f1facd2/href">https://medium.com/media/b13d3981395b2e3dcd2a137b1f1facd2/href</a></iframe><h3><strong>Importing Libraries</strong></h3><pre>from sklearn.datasets import fetch_california_housing<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.model_selection import train_test_split<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import scipy.stats as stats<br>import numpy as np<br>from matplotlib.colors import LinearSegmentedColormap<br>from mgwr.gwr import GWR<br>from mgwr.sel_bw import Sel_BW<br>from mgwr.utils import shift_colormap</pre><h3><strong>Collecting the Data</strong></h3><pre>housing = fetch_california_housing()<br>df = pd.DataFrame(columns=housing.feature_names, data=housing.data)</pre><p>Let’s take a look at the data we have.</p><pre>print(housing.DESCR)<br>print(df.info())<br>print(df.describe())</pre><pre>.. _california_housing_dataset:<br><br>California Housing dataset<br>--------------------------<br><br>**Data Set Characteristics:**<br><br>:Number of Instances: 20640<br><br>:Number of Attributes: 8 numeric, predictive attributes and the target<br><br>:Attribute Information:<br>    - MedInc        median income in block group<br>    - HouseAge      median house age in block group<br>    - AveRooms      average number of rooms per household<br>    - AveBedrms     average number of bedrooms per household<br>    - Population    block group population<br>    - AveOccup      average number of household members<br>    - Latitude      block group latitude<br>    - Longitude     block group longitude<br><br>:Missing Attribute Values: None<br><br>This dataset was obtained from the StatLib repository.<br>https://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html<br><br>The target variable is the median house value for California districts,<br>expressed in hundreds of thousands of dollars ($100,000).<br><br>This dataset was derived from the 1990 U.S. census, using one row per census<br>block group. A block group is the smallest geographical unit for which the U.S.<br>Census Bureau publishes sample data (a block group typically has a population<br>of 600 to 3,000 people).<br><br>A household is a group of people residing within a home. Since the average<br>number of rooms and bedrooms in this dataset are provided per household, these<br>columns may take surprisingly large values for block groups with few households<br>and many empty houses, such as vacation resorts.<br><br>It can be downloaded/loaded using the<br>:func:`sklearn.datasets.fetch_california_housing` function.<br><br>.. rubric:: References<br><br>- Pace, R. Kelley and Ronald Barry, Sparse Spatial Autoregressions,<br>  Statistics and Probability Letters, 33 (1997) 291-297<br><br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 20640 entries, 0 to 20639<br>Data columns (total 8 columns):<br> #   Column       Non-Null Count  Dtype  <br>---  ------       --------------  -----  <br> 0   MedInc       20640 non-null  float64<br> 1   HouseAge     20640 non-null  float64<br> 2   AveRooms     20640 non-null  float64<br> 3   AveBedrms    20640 non-null  float64<br> 4   Population   20640 non-null  float64<br> 5   AveOccup     20640 non-null  float64<br> 6   Latitude     20640 non-null  float64<br> 7   Longitude    20640 non-null  float64<br> 8   MedHouseVal  20640 non-null  float64<br>dtypes: float64(8)<br>memory usage: 1.3 MB<br>None<br><br>|        |   MedInc |   HouseAge |   AveRooms |   AveBedrms |   Population |   AveOccup |   Latitude |   Longitude |   MedHouseVal |<br>|--------|----------|------------|------------|-------------|--------------|------------|------------|-------------|---------------|<br>| count  | 20640    | 20640      | 20640      | 20640       | 20640        | 20640      | 20640      | 20640       | 20640         |<br>| mean   | 3.870671 | 28.639486  | 5.429      | 1.096675    | 1425.476744  | 3.070655   | 35.631861  | -119.569704 | 2.068558      |<br>| std    | 1.899822 | 12.585558  | 2.474173   | 0.473911    | 1132.462122  | 10.38605   | 2.135952   | 2.003532    | 1.153956      |<br>| min    | 0.4999   | 1          | 0.846154   | 0.333333    | 3            | 0.692308   | 32.54      | -124.35     | 0.14999       |<br>| 25%    | 2.5634   | 18         | 4.440716   | 1.006079    | 787          | 2.429741   | 33.93      | -121.8      | 1.196         |<br>| 50%    | 3.5348   | 29         | 5.229129   | 1.04878     | 1166         | 2.818116   | 34.26      | -118.49     | 1.797         |<br>| 75%    | 4.74325  | 37         | 6.052381   | 1.099526    | 1725         | 3.282261   | 37.71      | -118.01     | 2.64725       |<br>| max    | 15.0001  | 52         | 141.909091 | 34.066667   | 35682        | 1243.33333 | 41.95      | -114.31     | 5.00001       |</pre><p>As we can clearly see it mentioned in the data description, since the average number of rooms and bedrooms in this dataset are provided <strong>per household</strong>, these columns may take surprisingly large values for block groups with few households and many empty houses, such as vacation resorts. This makes the data fields positively skewed, or right-skewed.</p><pre>skew_rooms = stats.skew(df[&#39;AveRooms&#39;])<br>skew_bedrooms = stats.skew(df[&#39;AveBedrms&#39;])<br>skew_occupancy = stats.skew(df[&#39;AveOccup&#39;])<br><br>plt.figure(figsize=(12, 5))<br>plt.subplot(1, 3, 1)<br>plt.hist(df[&#39;AveRooms&#39;], bins=50, edgecolor=&#39;black&#39;)<br>plt.title(f&#39;AveRooms Distribution (Skewness = {skew_rooms:.2f})&#39;)<br>plt.xlabel(&#39;Average Rooms per Household&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br><br>plt.subplot(1, 3, 2)<br>plt.hist(df[&#39;AveBedrms&#39;], bins=50, edgecolor=&#39;black&#39;, color=&#39;orange&#39;)<br>plt.title(f&#39;AveBedrms Distribution (Skewness = {skew_bedrooms:.2f})&#39;)<br>plt.xlabel(&#39;Average Bedrooms per Household&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br><br>plt.subplot(1, 3, 3)<br>plt.hist(df[&#39;AveOccup&#39;], bins=50, edgecolor=&#39;black&#39;, color=&#39;green&#39;)<br>plt.title(f&#39;AveOccup Distribution (Skewness = {skew_occupancy:.2f})&#39;)<br>plt.xlabel(&#39;Average Occupancy per Household&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3NDpRI7g0Zizr1p6Uzt-w.png" /><figcaption>Extreme right-skewed distributions driven by sparsely populated or vacation-heavy block groups</figcaption></figure><h3><strong>Clean and preprocess the data</strong></h3><ul><li>The California Housing Dataset has no missing values so we do not need to handle missing values.</li><li>The data fields AveRooms, AveBedrms, and AveOccup are all heavily right-skewed, with most households having a low average number of rooms, and a long tail stretching toward higher values or with a massive spike at low values and a very long tail.</li><li>These skewed features can <strong>distort regression models</strong> or other statistical analyses if not handled properly.</li><li><strong>What we can do:</strong> To handle the right-skewed data fields, we can apply a log transformation to achieve a near normal distribution and then we can scale the data field like any other data field. <strong>Standard Scaling alone</strong> won’t fix skewness — it assumes normality and will preserve the long tail. And <strong>removing outliers</strong> might lose valuable geographic or socioeconomic signals, especially in census data.</li></ul><pre>df[&#39;_log1pTransformed_AveRooms&#39;] = df[&#39;AveRooms&#39;].apply(lambda x: np.log1p(x))<br>df[&#39;_log1pTransformed_AveBedrms&#39;] = df[&#39;AveBedrms&#39;].apply(lambda x: np.log1p(x))<br>df[&#39;_log1pTransformed_AveOccup&#39;] = df[&#39;AveOccup&#39;].apply(lambda x: np.log1p(x))</pre><pre>| Statistic | MedInc   | HouseAge | AveRooms  | AveBedrms | Population | AveOccup  | Latitude | Longitude  | MedHouseVal | AveRoomsTransformed  |<br>|-----------|----------|----------|-----------|-----------|------------|-----------|----------|------------|-------------|----------------------|<br>| count     | 20640.00 | 20640.00 | 20640.00  | 20640.00  | 20640.00   | 20640.00  | 20640.00 | 20640.00   | 20640.00    | 20640.00             |<br>| mean      | 3.870671 | 28.639486| 5.429000  | 1.096675  | 1425.476744| 3.070655  | 35.631861| -119.569704| 2.068558    | 1.828722             |<br>| std       | 1.899822 | 12.585558| 2.474173  | 0.473911  | 1132.462122| 10.386050 | 2.135952 | 2.003532   | 1.153956    | 0.231938             |<br>| min       | 0.499900 | 1.000000 | 0.846154  | 0.333333  | 3.000000   | 0.692308  | 32.540000| -124.350000| 0.149990    | 0.613104             |<br>| 25%       | 2.563400 | 18.000000| 4.440716  | 1.006079  | 787.000000 | 2.429741  | 33.930000| -121.800000| 1.196000    | 1.693911             |<br>| 50%       | 3.534800 | 29.000000| 5.229129  | 1.048780  | 1166.000000| 2.818116  | 34.260000| -118.490000| 1.797000    | 1.829236             |<br>| 75%       | 4.743250 | 37.000000| 6.052381  | 1.099526  | 1725.000000| 3.282261  | 37.710000| -118.010000| 2.647250    | 1.953365             |<br>| max       | 15.000100| 52.000000| 141.909091| 34.066667 | 35682.00000| 1243.33333| 41.950000| -114.310000| 5.000010    | 4.962209             |</pre><p>Now we can see that the difference between the 75% and max values have lesser magnitude in the transformed data field.</p><pre>skew_rooms = stats.skew(df[&#39;_log1pTransformed_AveRooms&#39;])<br>skew_bedrooms = stats.skew(df[&#39;_log1pTransformed_AveBedrms&#39;])<br>skew_occupancy = stats.skew(df[&#39;_log1pTransformed_AveOccup&#39;])<br><br>plt.figure(figsize=(12, 5))<br>plt.subplot(1, 3, 1)<br>plt.hist(df[&#39;_log1pTransformed_AveRooms&#39;], bins=50, edgecolor=&#39;black&#39;)<br>plt.title(f&#39;AveRooms Transformed (Skewness = {skew_rooms:.2f})&#39;)<br>plt.xlabel(&#39;Average Rooms per Household&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br><br>plt.subplot(1, 3, 2)<br>plt.hist(df[&#39;_log1pTransformed_AveBedrms&#39;], bins=50, edgecolor=&#39;black&#39;, color=&#39;orange&#39;)<br>plt.title(f&#39;AveBedrms Transformed (Skewness = {skew_bedrooms:.2f})&#39;)<br>plt.xlabel(&#39;Average Bedrooms per Household&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br><br>plt.subplot(1, 3, 3)<br>plt.hist(df[&#39;_log1pTransformed_AveOccup&#39;], bins=50, edgecolor=&#39;black&#39;, color=&#39;green&#39;)<br>plt.title(f&#39;AveOccup Transformed (Skewness = {skew_occupancy:.2f})&#39;)<br>plt.xlabel(&#39;Average Occupancy per Household&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOI2mpgxXx4aF9PgxiGJlA.png" /><figcaption>Significantly reduced skewness for rooms and bedrooms after log transformation</figcaption></figure><ul><li>When we say a feature has <strong>standard deviation (std) = 1</strong>, especially after applying something like StandardScaler, it means the data has been <strong>normalized</strong> so that the <strong>mean</strong> of the feature is <strong>0 </strong>and the <strong>spread</strong> of the data (standard deviation) is <strong>1.</strong></li></ul><p>This is useful because it puts all features on the <strong>same scale</strong>, regardless of their original units or ranges.</p><ul><li>Since the dataset contains only numerical features, so no categorical encoding is required.</li><li><strong>Train-Test Split:</strong> Split the dataset into training and testing sets to evaluate model performance fairly. We split both the original data frame and the scaled one.</li></ul><pre>target = &#39;MedHouseVal&#39;<br>features = [&#39;MedInc&#39;, &#39;HouseAge&#39;, &#39;Population&#39;, &#39;Latitude&#39;, &#39;Longitude&#39;,<br>            &#39;_log1p_AveRooms&#39;, &#39;_log1p_AveBedrms&#39;, &#39;_log1p_AveOccup&#39;]<br>X = df[features]<br>y = df[target]<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br>X_test_scaled = scaler.transform(X_test)</pre><ul><li><strong>Feature Scaling:</strong> Since features have different ranges and scales (e.g., Median Income vs. Latitude), applying feature scaling such as Standardization (z-score) or Min-Max scaling can help linear regression models perform better. We will save the scaled features in a new data frame so that our approach is non-destructive and we will also prevent information leakage by scaling the training dataset which has no contact with the test set anymore. <strong>Data leakage</strong> occurs when your model is trained on information that it <strong>shouldn’t have access to</strong> — especially data that would not be available at prediction time in a real-world scenario.</li></ul><pre>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br>X_test_scaled = scaler.transform(X_test)</pre><h3><strong>Exploratory Data Analysis</strong></h3><pre># Append target variable to df_train for exploratory analysis<br># EDA is restricted to the training set to prevent any information <br># leakage into the test set<br>df_train = pd.DataFrame(X_train, columns=housing.feature_names)<br>df_train[&#39;MedHouseVal&#39;] = y_train</pre><p>To better understand the California Housing dataset, we must conduct an exploratory data analysis (EDA) focusing on the distribution of key variables and their relationships.</p><pre>def plot_income_vs_rooms(ax, df):<br>    df_bin = df.copy()<br>    # Let&#39;s create Income range bins to better represent our data<br>    df_bin[&quot;MedInc_bin&quot;] = pd.qcut(df_bin[&quot;MedInc&quot;], 20)<br>    <br>    # The AveRooms field contains<br>    df_bin[&quot;ScaledAveRooms&quot;] = np.log1p(df_bin[&quot;AveRooms&quot;])<br>    avg_rooms = df_bin.groupby(&quot;MedInc_bin&quot;)[&quot;ScaledAveRooms&quot;].mean()<br>    bin_centers = df_bin.groupby(&quot;MedInc_bin&quot;)[&quot;MedInc&quot;].mean()<br>    ax.plot(bin_centers, avg_rooms, color=&quot;orange&quot;, marker=&quot;o&quot;, lw=2, ms=6, zorder=3)<br>    ax.text(0, 4, &quot;Income vs Rooms \nin California Housing&quot;,<br>            fontsize=16, fontweight=&quot;bold&quot;, color=&quot;white&quot;, family=&quot;monospace&quot;)<br>    ax.text(0.5, 0, &quot;Median Income (x-axis)&quot;, fontsize=11,<br>            color=&quot;white&quot;, family=&quot;monospace&quot;)<br>    ax.text(0.02, 0.5, &quot;log(1 + Average Rooms) (y-axis)&quot;, rotation=&quot;vertical&quot;,<br>            fontsize=11, color=&quot;white&quot;, family=&quot;monospace&quot;)</pre><p>The kernel density plots highlight the statistical distributions of three important attributes:</p><ul><li><strong>Property Age (HouseAge):</strong> The housing stock is spread across different age groups, with visible peaks around 20–30 and 40–50 years, indicating periods of concentrated housing development.</li><li><strong>Median Income (MedInc):</strong> Household income distribution is right-skewed, with the majority of households earning below $6,000 (in dataset units), while higher-income households are relatively sparse.</li><li><strong>Median House Value (MedHouseVal):</strong> Property values also show a right-skewed distribution, with the highest density around $2,000–$3,000 (in dataset units).</li></ul><h4>Bivariate Relationship: Income vs. Rooms</h4><p>A hexbin plot was used to visualize the relationship between <strong>median income (x-axis)</strong> and the <strong>log-transformed average number of rooms (y-axis)</strong>. The densest clusters appear in the mid-income range, suggesting a positive but nonlinear association between household income and room availability. The fitted line confirms that higher income levels are generally associated with larger housing units.</p><pre>df_bin = df_train.copy()<br>df_bin[&quot;MedInc_bin&quot;] = pd.qcut(df_bin[&quot;MedInc&quot;], 20)  # 20 quantile bins<br>avg_rooms = df_bin.groupby(&quot;MedInc_bin&quot;)[&quot;AveRooms&quot;].mean()<br><br>avg_rooms.plot(kind=&quot;line&quot;, marker=&quot;o&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*GD8H9t229wTPBgCl5QmQTQ.png" /><figcaption><strong>Relationship Between Median Income and Average Number of Rooms (California Housing Dataset)</strong></figcaption></figure><p>This plot shows the <strong>average number of rooms per household for each income quantile</strong> in the California Housing dataset.</p><ul><li>There is a <strong>strong, positive relationship</strong> between <strong>median income</strong> and <strong>average rooms per household</strong>.</li><li>As median income increases (moving right along the x-axis quantile bins), the average household size — measured by the number of rooms — increases steadily.</li><li>Higher-income neighborhoods tend to have <strong>larger homes</strong> with more rooms, indicating greater living space and likely higher property values.</li><li>For investors, this trend reveals that <strong>property size and wealth are correlated</strong> — targeting higher-income areas may offer properties with bigger floor plans and potentially increased market value.</li></ul><p>This is a typical pattern showing socioeconomic disparity in housing characteristics: wealthier areas have larger homes with more amenities</p><h3>Correlation Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*7X_q07ZEujryQe48IoMmnA.png" /></figure><p>The correlation heatmap reveals the relationships among the dataset’s features:</p><ul><li><strong>Median Income</strong> shows the strongest positive correlation with <strong>Median House Value</strong>, as expected.</li><li><strong>Average Rooms</strong> is positively correlated with income and house value but again house value is negatively associated with <strong>Average Bedrooms</strong>, reflecting the trade-off between total rooms and bedroom density impacting the property value. This pattern implies that homes with more bedrooms may be less valuable, which aligns with the idea that such properties are often used for rentals or shared living arrangements, rather than premium single-family residences.</li><li><strong>Geographical features</strong> (latitude and longitude) demonstrate weak but notable correlations with income and property values, highlighting location as a secondary determinant.</li><li>Other demographic variables, such as <strong>population</strong> and <strong>household size</strong>, exhibit minimal correlation with property value, suggesting their influence is less direct.</li></ul><p>The EDA indicates that <strong>income and number of rooms are strong predictors of property value</strong>, while geographic location further contributes to variation across the dataset. These insights guide the subsequent modeling approach by emphasizing the importance of socioeconomic and structural variables.</p><h3><strong>Empowering Strategic Decisions Through Data Analytics</strong></h3><p>Data analytics empowers investors and stakeholders to make informed decisions by transforming raw data into actionable insights. Through techniques like predictive modeling, trend analysis, and real-time dashboards, analytics reveals patterns in market behavior, consumer preferences, and operational performance. This enables stakeholders to assess risks, forecast returns, and identify growth opportunities with greater precision. For example, analyzing housing data can uncover correlations between income levels and property values, guiding investment strategies in real estate. Ultimately, data-driven decision-making reduces uncertainty, enhances strategic planning, and fosters confidence in navigating complex business environments.</p><p>In the upcoming sections, we will delve into several pivotal questions that play a crucial role in driving informed business decisions.</p><h3><strong>Where Are the Highest-Value Locations?</strong></h3><p>Understanding the geographic distribution of property values is essential for investors, urban planners, and policymakers aiming to identify high-return opportunities and optimize resource allocation. In this section, we explore how spatial patterns — defined by combinations of latitude and longitude — correlate with median house values. We also examine whether premium locations share common demographic or socioeconomic traits. By applying advanced spatial analytics and predictive modeling techniques, we aim to uncover not only where value is concentrated today, but also where it may emerge in the future.</p><pre>df_grid = df_train.copy()<br>df_grid[&#39;lat_bin&#39;] = pd.cut(df_grid[&#39;Latitude&#39;], bins=20)<br>df_grid[&#39;lon_bin&#39;] = pd.cut(df_grid[&#39;Longitude&#39;], bins=20)<br><br>heatmap_data = df_grid.groupby([&#39;lat_bin&#39;, &#39;lon_bin&#39;])[&#39;MedHouseVal&#39;].median().unstack()<br><br>plt.figure(figsize=(12,8))<br>sns.heatmap(heatmap_data, cmap=&#39;magma&#39;)<br>plt.title(&quot;Median Property Value by Geographic Region&quot;)<br>plt.xlabel(&quot;Longitude Bin&quot;)<br>plt.ylabel(&quot;Latitude Bin&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*nTYR6PP26r-gYrFGIjK8gw.png" /><figcaption>Median Property Value By geographic Region</figcaption></figure><ul><li><strong>High-value regions</strong> are clearly clustered in specific geographic bins, indicated by lighter colors on the heatmap.</li><li>These clusters suggest that certain neighborhoods or regions consistently command higher median property values, likely due to factors such as proximity to urban centers, coastal access, infrastructure, or socioeconomic status.</li><li><strong>Investors</strong> can use this spatial insight to target high-performing regions for acquisition or development.</li><li><strong>Urban planners</strong> may identify underserved areas or regions with potential for revitalization.</li><li><strong>Policy makers</strong> can assess regional disparities and plan equitable housing strategies.</li></ul><p>To enhance the accuracy of our house price prediction model, we aim to incorporate spatial context as a secondary determinant. Geographic coordinates (latitude and longitude) exhibit consistent correlations with income and property values, they might provide valuable insight into regional variation. To capture this spatial heterogeneity and account for varying scales of influence across predictors, we employ <strong>Multiscale Geographically Weighted Regression (MGWR)</strong> — a technique designed to model localized relationships and uncover spatially varying processes. Our approach is informed by the methodology outlined in the MGWR paper: <a href="https://www.mdpi.com/2220-9964/8/6/269">Investigating Process Spatial Heterogeneity and Scale</a>.</p><h3>GWR (Geographically Weighted Regression)</h3><p>Imagine you’re trying to predict house prices across California. A regular regression model gives you <strong>one rule for the whole state</strong>, like:</p><blockquote>“For every extra room, add ₹5 lakhs to the price.”</blockquote><p>But that’s too simplistic. What if rooms matter more in San Francisco than in Fresno?</p><p><strong>GWR says:</strong></p><blockquote>“Let’s make different rules for different places.”</blockquote><p>It looks at each location and builds a <strong>local regression model</strong>, so the effect of rooms, income, or age can change depending on where you are. It’s like saying:</p><blockquote>“In LA, income boosts house prices a lot. In Bakersfield, not so much.”</blockquote><pre>def gwr_analysis(df, coords_cols, y_col, X_cols):<br>    &quot;&quot;&quot;<br>    Perform Geographically Weighted Regression (GWR).<br><br>    Parameters:<br>    - df: pandas DataFrame containing data<br>    - coords_cols: list with two strings, names of lat and lon columns<br>    - y_col: string, name of target column<br>    - X_cols: list of strings, predictor columns<br><br>    Returns:<br>    - results: GWR results object with summary and diagnostics<br>    &quot;&quot;&quot;<br>    # Prepare coordinates and data arrays<br>    coords = df[coords_cols].values<br>    y = df[y_col].values.reshape((-1, 1))<br>    X = df[X_cols].values<br><br>    # Select optimal bandwidth<br>    selector = Sel_BW(coords, y, X)<br>    bandwidth = selector.search(bw_min=2)<br><br>    # Fit GWR model<br>    gwr_model = GWR(coords, y, X, bw=bandwidth)<br>    gwr_results = gwr_model.fit()<br><br>    return gwr_results<br><br>def plot_gwr_diagnostics(results):<br>    &quot;&quot;&quot;<br>    Plot GWR residuals and local coefficient surfaces.<br><br>    Parameters:<br>    - results: GWR results object<br>    &quot;&quot;&quot;<br>    # Residuals plot<br>    plt.figure(figsize=(10, 6))<br>    plt.scatter(range(len(results.resid_response)), results.resid_response, alpha=0.7)<br>    plt.axhline(0, color=&#39;red&#39;, linestyle=&#39;dashed&#39;)<br>    plt.title(&#39;GWR Residuals&#39;)<br>    plt.xlabel(&#39;Observation&#39;)<br>    plt.ylabel(&#39;Residual&#39;)<br>    plt.show()<br><br>    # Example: Plot local coefficient for first predictor<br>    coefs = results.params[:, 1]  # intercept is column 0; first predictor column 1<br>    plt.figure(figsize=(10, 6))<br>    sc = plt.scatter(results.model.coords[:, 0] , results.model.coords[:, 1], c=coefs, cmap=&#39;viridis&#39;)<br>    # plt.colorbar(sc, label=&#39;Local Coefficient for &#39; + results.X_names[1])<br>    plt.title(&#39;GWR Local Coefficients&#39;)<br>    plt.xlabel(&#39;Latitude&#39;)<br>    plt.ylabel(&#39;Longitude&#39;)<br>    plt.show()</pre><pre>predictors = [&#39;MedInc&#39;, &#39;HouseAge&#39;, &#39;AveRooms&#39;, &#39;Population&#39;, &#39;AveOccup&#39;]<br>gwr_results = gwr_analysis(df_train, coords_cols=[&#39;Latitude&#39;, &#39;Longitude&#39;], y_col=&#39;MedHouseVal&#39;, X_cols=predictors)<br>print(gwr_results.summary())<br><br>plot_gwr_diagnostics(gwr_results)</pre><h4>Result</h4><pre>Bandwidth used:                                                      75.000<br><br>Diagnostic information<br>---------------------------------------------------------------------------<br>Residual sum of squares:                                           1868.221<br>Effective number of parameters (trace(S)):                         3142.202<br>Degree of freedom (n - trace(S)):                                 13369.798<br>Sigma estimate:                                                       0.374<br>Log-likelihood:                                                   -5438.856<br>AIC:                                                              17164.117<br>AICc:                                                             18642.724<br>BIC:                                                              41403.999<br>R2:                                                                   0.915<br>Adjusted R2:                                                          0.895<br>Adj. alpha (95%):                                                     0.000<br>Adj. critical t value (95%):                                          3.903<br><br>Summary Statistics For GWR Parameter Estimates<br>---------------------------------------------------------------------------<br>Variable                   Mean        STD        Min     Median        Max<br>-------------------- ---------- ---------- ---------- ---------- ----------<br>X0                        1.204      1.021     -3.038      1.075      6.575<br>X1                        0.163      0.137     -0.928      0.150      1.181<br>X2                       -0.002      0.015     -0.070     -0.003      0.091<br>X3                        0.160      0.195     -1.046      0.124      1.214<br>X4                        0.000      0.000     -0.001      0.000      0.001<br>X5                       -0.233      0.290     -2.087     -0.172      0.944<br>===========================================================================</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*XcIqD7Zq2pvVcY6wrM_MLA.png" /><figcaption>A Diagnostic plot that visualizes how well Geographically Weighted Regression (GWR) model fits the data across all observations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*J4lFyUFEwpDKlziYb94Ndg.png" /><figcaption>Spatial variation in the effect of a predictor</figcaption></figure><p>Our analysis reveals that <strong>property values in California are not uniformly distributed</strong>, but instead exhibit distinct spatial clustering. The heatmap visualization of median house values across latitude-longitude bins highlights <strong>high-value regions concentrated near coastal and urban centers</strong>, suggesting that geographic location — while not the primary driver — is a meaningful secondary determinant of housing prices.</p><p>By applying <strong>Geographically Weighted Regression (GWR)</strong>, we captured how the influence of predictors like median income, house age, and average rooms <strong>varies across space</strong>. The model achieved a strong fit (R² = 0.915, Adjusted R² = 0.895), indicating that local variations in socioeconomic and structural features significantly improve predictive accuracy compared to global models.</p><p>Key takeaways from the GWR diagnostics:</p><ul><li><strong>Income (X1)</strong> shows a strong and spatially variable positive effect on house prices, with higher coefficients in affluent urban areas.</li><li><strong>Population (X3)</strong> also demonstrates spatial heterogeneity, suggesting that density impacts value differently across regions.</li><li><strong>Average Occupancy (X5)</strong> has a negative effect in most areas, but the magnitude varies, possibly reflecting overcrowding penalties in high-demand zones.</li></ul><p>These findings underscore the importance of <strong>spatial context in real estate analytics</strong>. Investors can leverage this localized intelligence to identify undervalued regions with growth potential. Urban planners and policymakers can use it to <strong>target interventions</strong>, promote equitable development, and anticipate future shifts in housing demand.</p><p>This will enhance our ability to forecast emerging high-value zones and support smarter, data-driven decision-making across the housing ecosystem.</p><p>// TODO<br>2. What Drives Property Value?</p><ul><li>Extends traditional regression by allowing coefficients to vary spatially.</li><li>Captures local relationships between house prices and predictors (income, age, rooms), acknowledging spatial heterogeneity.</li><li>Useful to identify zones where factors have stronger or weaker effects on prices.</li><li>Requires specialized libraries like mgwr or spglm in Python.</li><li><strong>Models/Methods:</strong></li><li><strong>Linear/Multiple Regression</strong> → quantify the influence of income, age, rooms.</li><li><strong>Random Forest / Gradient Boosting (XGBoost, LightGBM)</strong> → feature importance ranking.</li><li><strong>SHAP (Shapley Additive Explanations)</strong> → interpret which features contribute most to price.</li><li><strong>Elastic Net / Lasso Regression</strong> → feature selection, avoid overfitting.</li></ul><h3>3. What Is the Relationship Between Income and Property Size?</h3><ul><li>Identify natural clusters/groups of properties based on location and/or features.</li><li>K-Means finds spherical clusters by minimizing distance to centroids; DBSCAN finds density-based clusters and can detect noise/outliers.</li><li>Clusters can reveal neighborhoods or market segments with similar price levels or characteristics.</li><li><strong>Models/Methods:</strong></li><li><strong>Regression Analysis (linear or polynomial)</strong> between income and average rooms.</li><li><strong>Piecewise Regression</strong> → detect thresholds beyond which property size increases disproportionately.</li><li><strong>Quantile Regression</strong> → capture differences across income brackets (not just the mean).</li></ul><h3>4. Is Age a Major Factor in Pricing?</h3><ul><li>Quantify the degree to which property prices are spatially clustered, dispersed, or random.</li><li>Moran’s I provides a global measure of spatial autocorrelation, indicating overall clustering tendency.</li><li>LISA (Local Indicators of Spatial Association) detects local clusters and spatial outliers, highlighting specific premium or depressed pockets.</li><li><strong>Models/Methods:</strong></li><li><strong>Regression models with interaction terms</strong> (HouseAge × Region).</li><li><strong>Spline Regression / Nonlinear Models</strong> → detect U-shaped trends (e.g., historic homes regain value).</li><li><strong>Random Forest Feature Importance</strong> → check contribution of house age.</li><li><strong>Time-series proxy (if extended data available)</strong> → analyze appreciation of older homes.</li></ul><h3>5. What Are the Outlier or High-Growth Areas?</h3><ul><li><strong>Models/Methods:</strong></li><li><strong>Outlier Detection</strong> (Isolation Forest, DBSCAN, Z-score) for unusual price/size growth.</li><li><strong>Residual Analysis from regression models</strong> → where observed values are much higher than predicted.</li><li><strong>Cluster Evolution Analysis</strong> (if multiple time snapshots are available) → emerging hotspots.</li></ul><h3>6. How Is Population Density Related to Value?</h3><ul><li><strong>Models/Methods:</strong></li><li><strong>Correlation/Regression</strong> between population and property value.</li><li><strong>Nonlinear Regression</strong> (e.g., log of population density vs. value).</li><li><strong>Spatial Regression Models</strong> → see how density interacts with latitude/longitude.</li><li><strong>Comparative Analysis</strong> → city center vs. suburbs segmentation.</li></ul><h3>7. What Is the Overall Distribution of Property Prices?</h3><ul><li><strong>Models/Methods:</strong></li><li><strong>Histograms, KDE plots, and boxplots</strong> of property values.</li><li><strong>Mixture Models (Gaussian Mixture)</strong> → segment market into affordable, mid-range, premium.</li><li><strong>Cluster Analysis</strong> → investment categories based on price + features.</li><li><strong>Lorenz Curve / Gini Coefficient</strong> → measure inequality in property prices.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f23202bba8ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Animating a Model using Media Pipe — Unity Project]]></title>
            <link>https://medium.com/@debasishraut.dev/animating-a-model-using-media-pipe-unity-project-d984b7f030f9?source=rss-5503dc1080a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d984b7f030f9</guid>
            <category><![CDATA[motion-capture]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[mediapipe]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Debasish Raut]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 21:19:44 GMT</pubDate>
            <atom:updated>2025-11-21T14:11:15.531Z</atom:updated>
            <content:encoded><![CDATA[<h3>Animating a Model using Media Pipe — Godot Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bjq5rPRiWDCRbNq6cYHWZg.jpeg" /></figure><p>Imagine capturing your every movement with a smartphone and transforming it into stunning 3D animations — without any need for any special motion capturing equipment. Anyone even remotely interested in animation has thought of this idea, an accessible, affordable motion capture for all your animation tasks. It is this very need for a solution that we embarked on the adventure of developing an Android/iOS app that uses simple video uploads or camera captures and transforms them into animations projected onto a Rigged 3D Model.</p><p>This article talks about the various technical specifications of the Media Pipe API and development hurdles that we faced and how we mitigated across those problems to find solutions that were optimal and effective. So let’s dive right into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jW9FVsa1G-tBSSDV2lxIBg.png" /></figure><p>We start by creating a flask app. Simple, isn’t it. But hold your horses! Make a virtual environment first. It gets messy afterwards, trust me. You could use python’s <em>venv </em>module, The <em>venv </em>module supports creating lightweight “virtual environments”. You could use conda for more robust environment management, but I personally like miniconda, which has all the benefits of conda but doesn’t come with all the other softwares I am never going to use anyway. In any case, create a virtual environment and activate it. For Mediapipe framework compatibility, we should use python 3.9, and therefore use the command</p><pre>conda create --name mediapipe_env python=3.9</pre><p>Then we need to install the flask module. Flask is a lightweight and flexible web framework written in Python, often referred to as a <strong>micro-framework</strong> because it provides the essentials for building web applications without imposing a rigid structure.</p><pre>pip install Flask</pre><p>Now let’s create the project. Create a folder, name it anything you like. Create a file called <em>server.py </em>inside this folder. This will be our file which will serve the API endpoints, and we will come back to it later, for now, we will leave it as it is.</p><p>Next let’s create another file called <em>pose_estimator.py</em>, which will host all our functions that are used to generate pose landmarks. Pose landmarks are three dimensional points, having x, y, and z values (and many more values but x, y, z values are what we will concern ourselves with). These points are generated by Google’s Media Pipe Pose Estimation Model. You can find more about this model and many more similar models each with their specific area of expertise <a href="https://ai.google.dev/edge/mediapipe/solutions/guide"><em>here</em></a>. For our task, let’s look at the Pose Estimation model. It says it plots 33 points, each corresponding to a joint/point in our body.</p><figure><img alt="Image showing MediaPipe Pose Landmar Points, shows 33 different points each correspoing to a body joint or a point of interest." src="https://cdn-images-1.medium.com/max/661/1*bDCA9-OpFA5pjePGzfiCwg.png" /><figcaption>MediaPipe Pose Landmarks</figcaption></figure><p><strong>Install the mediapipe library:</strong></p><p>You can search for the keywords “mediapipe install python” and you should be directed to their official documentation page <a href="https://ai.google.dev/edge/mediapipe/solutions/guide">https://ai.google.dev/edge/mediapipe/solutions/guide</a>. From there, go to the platform setup guides and bookmark the page as we will be visiting this page more than once. For now let’s set up mediapipe for python. Once in <a href="https://ai.google.dev/edge/mediapipe/solutions/setup_python">https://ai.google.dev/edge/mediapipe/solutions/setup_python</a> you can see that mediapipe works well in Python: version 3.9 to 3.12, and since we have created a miniconda environment(or any python environment that you have created) using python version 3.9 we are in the safe zone and we are ready to proceed further. Before running a MediaPipe task on a Python application, install the MediaPipe package:</p><pre>$ python -m pip install mediapipe</pre><p>Next we will need the Open Computer Vision Library for video processing and landmark detection tasks. Mediapipe library already comes with the compatible version of opencv-contrib-python so we do not need to worry about installing compatible versions again.</p><p><strong>Let’s see our model in action.</strong></p><p>Currently we have our libraries in place, but we are missing a key part, the actual pre-trained model that we will be using. The MediaPipe Pose Landmarker task requires a trained model that is compatible with this task. Take a look at the <a href="https://ai.google.dev/edge/mediapipe/solutions/vision/pose_landmarker/index#models">Models section</a> that lists lite, full and heavy duty models. For our demonstration part, I like to use the full version of the model so let’s go ahead and download that. And the next thing we need is a video of a human doing something in a static frame of reference, and for this part I have chosen a dance video which should serve as a great sample to test out some complex human movements and poses that we are going to interpolate. So save the models and the videos in their own place, as a best practice, I like to structure my files like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*D5uiAZ5K8vQP0WxEDwRUxw.png" /><figcaption>File structure of the project</figcaption></figure><p>Keep all the stuff like images, videos and anything that we need as input or for reference inside Assets folder. The models folder houses the pre-trained models that we are going to use and in future it will also help us organize our specific use-case trained models(for example we just want to detect pose when the user makes a certain trigger gesture, like the flick of a hand to start the process etc). The out folder houses the outputs, and for this demonstration we will put our outputs into this folder. The src or the source code folder is where we will keep all our code.</p><p>In the src folder, let’s create our file where we can code. Jupyter notebook is a great tool for this as we just need to make sure everything is working as expected. So Let’s go ahead and create the file /src/init.ipynb and in here we will first import the libraries and set our paths to our models, assets and output folder paths.</p><p>Import the necessary modules:</p><pre>import cv2<br>import mediapipe as mp<br>import numpy as np<br><br>import matplotlib.pyplot as plt<br>from collections import deque</pre><p>Next we set our variables:</p><pre>videoPath = &quot;../Assets/mediapipe_female.mp4&quot;<br>vidoeOutPath = &quot;../out/mp_annot.mp4&quot;<br>modelPath = &quot;../models/pose_landmarker_full.task&quot;</pre><p>Next we initialize the open cv video capture to let us process a video frame by frame and we will also initialize a video writer to write our output.</p><pre>def init_video(video_path):<br>    cap = cv2.VideoCapture(video_path)<br>    fps = cap.get(cv2.CAP_PROP_FPS)<br>    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))<br>    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))<br>    return cap, fps, frame_width, frame_height<br><br>def init_writer(out_path, fourcc, fps, dimensions):<br>    return cv2.VideoWriter(out_path, fourcc, fps, dimensions)</pre><p>Next we will initialize the pose detection model:</p><pre>def init_pose_detector(model_path):<br>    BaseOptions = mp.tasks.BaseOptions<br>    PoseLandmarker = mp.tasks.vision.PoseLandmarker<br>    PoseLandmarkerOptions = mp.tasks.vision.PoseLandmarkerOptions<br>    VisionRunningMode = mp.tasks.vision.RunningMode<br>    options = PoseLandmarkerOptions(<br>        base_options=BaseOptions(model_asset_path=model_path),<br>        running_mode=VisionRunningMode.VIDEO)<br>    return PoseLandmarker.create_from_options(options)</pre><ul><li>BaseOptions is used to load the AI model (the .tflite file).</li><li>PoseLandmarker is the main class that performs pose detection.</li><li>PoseLandmarkerOptions lets you configure how the model should run.</li><li>VisionRunningMode tells the model if it should process <strong>images, video, or live streaming</strong>.</li></ul><p>For viewing our output and how the mediapipe model is working, we will need to project the pose landmark as annotations in out video frame by frame. For this specific purpose, mediapipe has provided utility functions under <strong>Visualization Utilities </strong>sections in their github samples</p><p><a href="https://github.com/google-ai-edge/mediapipe-samples/blob/main/examples/pose_landmarker/python/%5BMediaPipe_Python_Tasks%5D_Pose_Landmarker.ipynb"><strong>mediapipe-samples/examples/pose_landmarker/python/[MediaPipe_Python_Tasks]_Pose_Landmarker.ipynb</strong></a></p><pre>#@markdown To better demonstrate the Pose Landmarker API, <br># we have created a set of visualization tools that <br># will be used in this colab. These will draw the landmarks on a <br># detect person, as well as the expected connections between those markers.<br><br>from mediapipe import solutions<br>from mediapipe.framework.formats import landmark_pb2<br>import numpy as np<br><br><br>def draw_landmarks_on_image(rgb_image, detection_result):<br>  pose_landmarks_list = detection_result.pose_landmarks<br>  annotated_image = np.copy(rgb_image)<br><br>  # Loop through the detected poses to visualize.<br>  for idx in range(len(pose_landmarks_list)):<br>    pose_landmarks = pose_landmarks_list[idx]<br><br>    # Draw the pose landmarks.<br>    pose_landmarks_proto = landmark_pb2.NormalizedLandmarkList()<br>    pose_landmarks_proto.landmark.extend([<br>      landmark_pb2.NormalizedLandmark(x=landmark.x, y=landmark.y, z=landmark.z) for landmark in pose_landmarks<br>    ])<br>    solutions.drawing_utils.draw_landmarks(<br>      annotated_image,<br>      pose_landmarks_proto,<br>      solutions.pose.POSE_CONNECTIONS,<br>      solutions.drawing_styles.get_default_pose_landmarks_style())<br>  return annotated_image</pre><p>These give access to drawing tools, styles, and the pose estimation model from Google’s <strong>MediaPipe</strong> library. They’ll be used later to <strong>detect human body landmarks</strong> and draw them on the video.</p><p>Next we want to process each frame through the Mediapipe Pose Landmarker model so we will write a process_frame function which will run inside a loop processing each frame and returning the resulting Pose Landmarks as well as the frame being processed so that we can re-use that frame in our image annotation function.</p><pre>def process_frame(image, pose_detector, timestamp_ms):<br>    mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=image)<br>    return (pose_detector.detect_for_video(mp_image, timestamp_ms), mp_image)</pre><p>Before we move onwards, we must understand what kind of data we are dealing with here. When we use process_frame function the pose_detector detect_for_video function is returning the PoseLandmarkerResult object which is a a list of lists of NormalizedLandmark objects. It also returns World Landmarks which is a list of lists of Landmark objects, representing the same keypoints but in real-world 3D coordinates (not normalized to the image). We will be using the world landmarks because our endgame use case is related to the conversion of mediapipe pose detections to 3D model animation keyframes.</p><p>Next we will open the video and for each frame, we will apply the pose detection and visualize our result in the main loop:</p><pre>def main_loop(video_path, out_path, model_path):<br>    cap, fps, width, height = init_video(video_path)<br>    fourcc = cv2.VideoWriter_fourcc(*&#39;mp4v&#39;)<br>    out = init_writer(out_path, fourcc, fps, (width, height))<br>    pose_detector = init_pose_detector(model_path)<br><br>    while cap.isOpened():<br>        success, image = cap.read()<br>        if not success:<br>            break<br>        timestamp_ms = int(cap.get(cv2.CAP_PROP_POS_MSEC))<br>        image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br>        result, mp_image = process_frame(image_rgb, pose_detector, timestamp_ms)<br><br>        if result.pose_world_landmarks:<br>            annotated_image = draw_landmarks_on_image(mp_image.numpy_view(), result.pose_landmarks)<br>            annotated_image_bgr = cv2.cvtColor(annotated_image, cv2.COLOR_RGB2BGR)<br>            out.write(annotated_image_bgr)<br><br>    cap.release()<br>    out.release()</pre><p>cap is like a camera feed, but here it’s reading frames from a file. It reads <strong>frames per second (fps)</strong> and <strong>frame dimensions (width and height)</strong>. This ensures the output video has the same properties as the input.</p><p>The above code also defines a <strong>video codec</strong> (mp4v) to save the processed video. cv2.VideoWriter creates an output file where processed frames will be written one by one. Notice that we use the same fps and dimensions as our original video. This is useful in comparing our input to the output.</p><p>This main_loop is like a factory line. Each frame of the video comes in, we convert it for the AI, the AI finds the body landmarks, we draw them on the frame, and then we save the new frame into the output video. By the end, we’ve created a new video with pose skeletons drawn on every frame.</p><p>When we run the loop we will get our result stored in the /out folder.</p><pre>main_loop(videoPath, vidoeOutPath, modelPath)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*aS5rlrhBT4oWpmS_zI-1KA.gif" /></figure><p>Now, while the pose landmarks are on point for each frame if considered each frame on an individual level, I bet you noticed the landmarks around her feet shaking is shaking which is not at all desired and something must be done about it.</p><p>In signal processing, we come across the concept of filters. Signals are wave forms and filters are transformations on these wave forms in-order to achieve some desired result, in many case that is the stabilization of the signal and the reduction of noise. We can treat our pose landmark points(x, y, and z positions) as a continual string of signals that can be stabilized using signal stabilization filters.</p><h4>Simple Moving Average (SMA)</h4><p>A <a href="https://www.investopedia.com/terms/s/sma.asp">simple moving average (SMA)</a> is calculated by taking the arithmetic mean of a given set of values over a specified period. This is as simple as it gets, we basically take the mean points in the neighborhood in order to smooth out the jitter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*mHZagYGPTyfY70GX6i-TOw.png" /></figure><p>We should start with this function as an experiment, and we can gradually move to more complex filter functions and compare our results as we go.</p><p>Let’s write a function that takes in a buffer of landmarks and returns the mean for the respective points.</p><pre>def transform_func(x, y, z, visibility, presence, landmark_buffers, idx):<br>    buffer = landmark_buffers[idx]<br>    buffer.append([x, y, z])<br>    if len(buffer) == buffer.maxlen:<br>        mean_x, mean_y, mean_z = np.mean(buffer, axis=0)<br>        return mean_x, mean_y, mean_z, visibility, presence<br>    else:<br>        return x, y, z, visibility, presence</pre><p>Notice how we are expecting a buffer of landmarks according to the window size set before applying Simple Moving Average. This buffer of landmarks are nothing but lists of 5 contiguous points per each joint. In order to store this buffer we need a new place to store all these information properly:</p><pre>buffers = {<br>        0: deque(maxlen=sma_window),<br>        1: deque(maxlen=sma_window),<br>        2: deque(maxlen=sma_window),<br>        3: deque(maxlen=sma_window),<br>        4: deque(maxlen=sma_window),<br>        5: deque(maxlen=sma_window),<br>        6: deque(maxlen=sma_window),<br>        7: deque(maxlen=sma_window),<br>        8: deque(maxlen=sma_window),<br>        9: deque(maxlen=sma_window),<br>        10: deque(maxlen=sma_window),<br>        11: deque(maxlen=sma_window),<br>        12: deque(maxlen=sma_window),<br>        13: deque(maxlen=sma_window),<br>        14: deque(maxlen=sma_window),<br>        15: deque(maxlen=sma_window),<br>        16: deque(maxlen=sma_window),<br>        17: deque(maxlen=sma_window),<br>        18: deque(maxlen=sma_window),<br>        19: deque(maxlen=sma_window),<br>        20: deque(maxlen=sma_window),<br>        21: deque(maxlen=sma_window),<br>        22: deque(maxlen=sma_window),<br>        23: deque(maxlen=sma_window),<br>        24: deque(maxlen=sma_window),<br>        25: deque(maxlen=sma_window),<br>        26: deque(maxlen=sma_window),<br>        27: deque(maxlen=sma_window),<br>        28: deque(maxlen=sma_window),<br>        29: deque(maxlen=sma_window),<br>        30: deque(maxlen=sma_window),<br>        31: deque(maxlen=sma_window),<br>        32: deque(maxlen=sma_window),<br>    }</pre><p>We can comment out the joints that we do not need to apply the transformation function to. For now, I will let this be as is. We need a transformation function to apply the transform_func function to all the required joints. For that we write the following function:</p><pre>def transform_landmarks(pose_landmarks_list, transform_func, landmark_buffers):<br>    &quot;&quot;&quot;<br>    Applies a transformation function (such as smoothing) to each landmark in each detected pose.<br><br>    Args:<br>        pose_landmarks_list (list of list): <br>            A list where each element is a list of landmark objects for a detected pose <br>            (e.g., from detection_result.pose_landmarks or detection_result.pose_world_landmarks).<br>        transform_func (callable): <br>            A function that takes (x, y, z, visibility, presence, landmark_buffers, idx) and returns <br>            transformed (x, y, z, visibility, presence) for each landmark.<br>        landmark_buffers (dict): <br>            A dictionary mapping landmark indices to buffers (e.g., deques) used for temporal smoothing <br>            or filtering of landmark coordinates.<br><br>    Returns:<br>        transformed_landmarks_list (list of list): <br>            A list of lists, where each inner list contains tuples of transformed (x, y, z, visibility, presence) <br>            for each landmark in a pose.<br>    &quot;&quot;&quot;<br>    transformed_landmarks_list = []<br>    if not pose_landmarks_list:<br>        return transformed_landmarks_list<br>    <br>    for pose_landmarks in pose_landmarks_list:<br>        transformed_landmarks = []<br>        for i, landmark in enumerate(pose_landmarks):<br>            x, y, z, v, p = landmark.x, landmark.y, landmark.z, landmark.visibility, landmark.presence<br>            x_t, y_t, z_t, v_t, p_t = transform_func(x, y, z, v, p, landmark_buffers, idx=i)<br>            transformed_landmarks.append((x_t, y_t, z_t, v_t, p_t))<br>        transformed_landmarks_list.append(transformed_landmarks)<br><br>    return transformed_landmarks_list</pre><p>It processes a list of detected poses, applying a transformation to each landmark in each pose. For each detected pose (which is a list of landmarks), it iterates through all landmarks and for each landmark, it extracts the coordinates and confidence values and then it calls the provided transform_func, passing the landmark data, the buffer for that landmark, and the landmark index. The transformed values are collected into a new list for that pose. Note that this is a simple python list and our PoseLandmarkerResult object was a list of lists of Landmark object. We need to convert the resultant list back to their original structure if we are to further process these pose detection landmarks. For that we need a specific function:</p><pre>def create_landmark_proto_from_points(transformed_landmarks):<br>    proto_landmarks = landmark_pb2.NormalizedLandmarkList()<br>    for idx in range(len(transformed_landmarks)):<br>        pose_landmarks = transformed_landmarks[idx]<br>        proto_landmarks.landmark.extend([<br>            landmark_pb2.NormalizedLandmark(<br>                x=x, y=y, z=z, visibility=visibility, presence=presence<br>            ) for (x, y, z, visibility, presence) in pose_landmarks<br>        ])<br>    return proto_landmarks</pre><p>This function converts your list of transformed landmarks (output by our SMA filter) into a format required by MediaPipe — NormalizedLandmarkList protobuf object. For every landmark in the pose’s list, it builds a NormalizedLandmark proto using values x, y, z, visibility, and presence . The function returns the filled NormalizedLandmarkList, ready for further processing.</p><p>Now all we need to do is transform our points using the transform_landmarks function which calls the transform_func function which is nothing but Simple Moving Average for each points. We can then feed this transformed points to our drawing annotation function for a vizualization of our smoothing function in action.</p><pre># main_loop:<br> . . .<br>transformed_points = transform_landmarks(result.pose_landmarks, transform_func, buffers)<br>proto_landmarks = create_landmark_proto_from_points(transformed_points)<br>annotated_image = draw_landmarks_on_image(mp_image.numpy_view(), proto_landmarks)<br>annotated_image_bgr = cv2.cvtColor(annotated_image, cv2.COLOR_RGB2BGR)<br> . . .</pre><p>And here is the final main loop that we have to implement:</p><pre>def main_loop(video_path, out_path, model_path, sma_window=5):<br>    cap, fps, width, height = init_video(video_path)<br>    fourcc = cv2.VideoWriter_fourcc(*&#39;mp4v&#39;)<br>    out = init_writer(out_path, fourcc, fps, (width, height))<br>    pose_detector = init_pose_detector(model_path)<br>    frame_count = 0<br>    buffers = {<br>        0: deque(maxlen=sma_window),<br>        1: deque(maxlen=sma_window),<br>        2: deque(maxlen=sma_window),<br>        3: deque(maxlen=sma_window),<br>        4: deque(maxlen=sma_window),<br>        5: deque(maxlen=sma_window),<br>        6: deque(maxlen=sma_window),<br>        7: deque(maxlen=sma_window),<br>        8: deque(maxlen=sma_window),<br>        9: deque(maxlen=sma_window),<br>        10: deque(maxlen=sma_window),<br>        11: deque(maxlen=sma_window),<br>        12: deque(maxlen=sma_window),<br>        13: deque(maxlen=sma_window),<br>        14: deque(maxlen=sma_window),<br>        15: deque(maxlen=sma_window),<br>        16: deque(maxlen=sma_window),<br>        17: deque(maxlen=sma_window),<br>        18: deque(maxlen=sma_window),<br>        19: deque(maxlen=sma_window),<br>        20: deque(maxlen=sma_window),<br>        21: deque(maxlen=sma_window),<br>        22: deque(maxlen=sma_window),<br>        23: deque(maxlen=sma_window),<br>        24: deque(maxlen=sma_window),<br>        25: deque(maxlen=sma_window),<br>        26: deque(maxlen=sma_window),<br>        27: deque(maxlen=sma_window),<br>        28: deque(maxlen=sma_window),<br>        29: deque(maxlen=sma_window),<br>        30: deque(maxlen=sma_window),<br>        31: deque(maxlen=sma_window),<br>        32: deque(maxlen=sma_window),<br>    }<br><br>    while cap.isOpened():<br>        success, image = cap.read()<br>        if not success:<br>            break<br>        timestamp_ms = int(cap.get(cv2.CAP_PROP_POS_MSEC))<br>        image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br>        result, mp_image = process_frame(image_rgb, pose_detector, timestamp_ms)<br>        print(result)<br>        frame_count += 1<br>        # if frame_count &gt; 2:  # break early for testing<br>        #     break<br>        if result.pose_world_landmarks:<br>            print(result)<br>            for idx in buffers.keys():<br>                x, y, z = (result.pose_landmarks[0][idx].x,<br>                           result.pose_landmarks[0][idx].y,<br>                           result.pose_landmarks[0][idx].z)<br>                avg = update_buffer(buffers[idx], [x, y, z])<br>                # print(f&quot;SMA Point {idx} → x: {avg[0] if avg else x:.4f}, y: {avg[1] if avg else y:.4f}, z: {avg[2] if avg else z:.4f}&quot;)<br><br>            transformed_points = transform_landmarks(result.pose_landmarks, transform_func, buffers)<br>            proto_landmarks = create_landmark_proto_from_points(transformed_points)<br>            # annotated_image = draw_landmarks_on_image(mp_image.numpy_view(), result)<br>            annotated_image = draw_landmarks_on_image(mp_image.numpy_view(), proto_landmarks)<br>            annotated_image_bgr = cv2.cvtColor(annotated_image, cv2.COLOR_RGB2BGR)<br>            out.write(annotated_image_bgr)<br><br>    cap.release()<br>    out.release()</pre><p>Running this implementation of our mediapipe pose landmarker model we get a somewhat smoother landmarks, although I can also see some visible lag that happens around the face because of it. Nonetheless, the final result is actually much more smoother. Here is the side by side comparison, the left side is the smoother version and the right side shows the original output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*xPTM8SgxeRoIvfI6o9LaMQ.gif" /></figure><p>Another such simple Speed-based Low-pass Filter for Noisy Input is <strong>One Euro Filter</strong>.</p><p>The 1€ filter (“one Euro filter”) is a simple algorithm to filter noisy signals for high precision and responsiveness. It uses a first order low-pass filter with an adaptive cutoff frequency: at low speeds, a low cutoff stabilizes the signal by reducing jitter, but as speed increases, the cutoff is increased to reduce lag. In out SMA implementation, if you look closely, you can see the landmarks lagging behind in cases where the movement is sudden and fast.</p><p>Mentioned in their paper:</p><blockquote>Noisy signals occur when an original time varying value undergoes undesirable and unpredictable perturbations. These may be caused by things like heat and magnetic fields affecting hardware circuitry, the limits of sensor resolution, or <strong>even unstable numerical computation</strong>. Noisy signals are a common problem when <strong>tracking human motion</strong>, particularly with custom sensing hardware and inexpensive input devices like the Kinect or Wiimote.</blockquote><p>As we have come to a stable solution, for now, we will refrain from including an advanced smoothing algorithm in our pipeline, and if the need truly arises sometime in the future(which it always does), we will come back here to create and include those in the pipeline eventually.</p><h4>Time to see our model in action</h4><p>Let’s write a class that handles all the tasks related to the pose landmarks.</p><pre>from config import MODEL_PATH, VIDEO_OUT_PATH, VIDEO_PATH, SMA_WINDOW<br><br>import cv2<br>import mediapipe as mp<br>import numpy as np<br>from collections import deque<br>from mediapipe.framework.formats import landmark_pb2<br>from mediapipe import solutions<br><br>class PoseEstimator:<br>    &quot;&quot;&quot;<br>    A class to handle pose estimation from video files using MediaPipe.<br>    Designed to be integrated with Flask servers for processing video and extracting pose landmarks.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, model_path: str, sma_window: int = SMA_WINDOW):<br>        &quot;&quot;&quot;<br>        Initialize the PoseEstimator with model path and smoothing window size.<br>        <br>        Args:<br>            model_path: Path to the MediaPipe pose landmarker model (.task file)<br>            sma_window: Simple Moving Average window size for landmark smoothing<br>        &quot;&quot;&quot;<br>        self.model_path = model_path<br>        self.sma_window = sma_window<br>        self.pose_detector = self._init_pose_detector()<br>        self.landmark_buffers = self._init_buffers()<br>        self.global_pose_landmarks_list = []<br>        <br>    def _init_buffers(self) -&gt; dict:<br>        &quot;&quot;&quot;<br>        Initialize deque buffers for each of the 33 pose landmarks.<br>        Each buffer stores the last `sma_window` frames of landmark coordinates.<br>        <br>        Returns:<br>            dict: Dictionary mapping landmark index to deque buffer<br>        &quot;&quot;&quot;<br>        return {i: deque(maxlen=self.sma_window) for i in range(33)}<br>    <br>    def _init_pose_detector(self) -&gt; mp.tasks.vision.PoseLandmarker:<br>        &quot;&quot;&quot;<br>        Initialize MediaPipe PoseLandmarker with VIDEO running mode.<br>        <br>        Returns:<br>            PoseLandmarker: Configured pose detection model<br>        &quot;&quot;&quot;<br>        BaseOptions = mp.tasks.BaseOptions<br>        PoseLandmarker = mp.tasks.vision.PoseLandmarker<br>        PoseLandmarkerOptions = mp.tasks.vision.PoseLandmarkerOptions<br>        VisionRunningMode = mp.tasks.vision.RunningMode<br>        <br>        options = PoseLandmarkerOptions(<br>            base_options=BaseOptions(model_asset_path=self.model_path),<br>            running_mode=VisionRunningMode.VIDEO<br>        )<br>        return PoseLandmarker.create_from_options(options)<br>    <br>    def _init_video_capture(self, video_path: str) -&gt; tuple:<br>        &quot;&quot;&quot;<br>        Initialize video capture and extract video properties.<br>        <br>        Args:<br>            video_path: Path to the video file<br>            <br>        Returns:<br>            tuple: (VideoCapture object, fps, frame_width, frame_height)<br>        &quot;&quot;&quot;<br>        cap = cv2.VideoCapture(video_path)<br>        fps = cap.get(cv2.CAP_PROP_FPS)<br>        frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))<br>        frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))<br>        return cap, fps, frame_width, frame_height<br>    <br>    def _process_frame(self, image: np.ndarray, timestamp_ms: int) -&gt; tuple:<br>        &quot;&quot;&quot;<br>        Process a single frame through the pose detector.<br>        <br>        Args:<br>            image: Frame in RGB format (numpy array)<br>            timestamp_ms: Timestamp in milliseconds for video frame<br>            <br>        Returns:<br>            tuple: (detection_result, mp.Image)<br>        &quot;&quot;&quot;<br>        mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=image)<br>        detection_result = self.pose_detector.detect_for_video(mp_image, timestamp_ms)<br>        return detection_result, mp_image<br>    <br>    def _transform_landmark(self, x: float, y: float, z: float, <br>                           visibility: float, presence: float, <br>                           landmark_idx: int) -&gt; tuple:<br>        &quot;&quot;&quot;<br>        Apply Simple Moving Average smoothing to a single landmark coordinate.<br>        <br>        Args:<br>            x, y, z: Landmark coordinates<br>            visibility: Landmark visibility score<br>            presence: Landmark presence score<br>            landmark_idx: Index of the landmark (0-32)<br>            <br>        Returns:<br>            tuple: (smoothed_x, smoothed_y, smoothed_z, visibility, presence)<br>        &quot;&quot;&quot;<br>        buffer = self.landmark_buffers[landmark_idx]<br>        buffer.append([x, y, z])<br>        <br>        if len(buffer) == buffer.maxlen:<br>            mean_x, mean_y, mean_z = np.mean(buffer, axis=0)<br>            return mean_x, mean_y, mean_z, visibility, presence<br>        else:<br>            return x, y, z, visibility, presence<br>    def transform_func(self, x, y, z, visibility, presence, landmark_buffers, idx):<br>        buffer = landmark_buffers[idx]<br>        buffer.append([x, y, z])<br>        if len(buffer) == buffer.maxlen:<br>            mean_x, mean_y, mean_z = np.mean(buffer, axis=0)<br>            return mean_x, mean_y, mean_z, visibility, presence<br>        else:<br>            return x, y, z, visibility, presence<br>    def _transform_landmarks(self, pose_landmarks_list: list, transform_func, landmark_buffers) -&gt; list:<br>        &quot;&quot;&quot;<br>        Applies transform_func to each landmark in each detected pose.<br><br>        Args:<br>            pose_landmarks_list: list of lists of landmarks (detection_result.pose_landmarks)<br>            transform_func: function that takes (x, y, z) and returns transformed (x, y, z)<br><br>        Returns:<br>            transformed_landmarks_list: list of lists of transformed landmarks as tuples (x, y, z)<br>        &quot;&quot;&quot;<br>        transformed_landmarks_list = []<br>        <br>        if not pose_landmarks_list:<br>            return transformed_landmarks_list<br>        <br>        for pose_landmarks in pose_landmarks_list:<br>            transformed_landmarks = []<br>            for i,landmark in enumerate(pose_landmarks):<br>                x, y, z, v, p = landmark.x, landmark.y, landmark.z, landmark.visibility, landmark.presence<br>                x_t, y_t, z_t, v_t, p_t = transform_func(x, y, z, v, p, landmark_buffers, idx=i)<br>                transformed_landmarks.append((x_t, y_t, z_t, v_t, p_t))<br>            <br>            transformed_landmarks_list.append(transformed_landmarks)<br>            self.global_pose_landmarks_list.append(transformed_landmarks)<br>        <br>        return transformed_landmarks_list<br>    <br>    def _create_landmark_proto(self, transformed_landmarks: list) -&gt; landmark_pb2.NormalizedLandmarkList:<br>        &quot;&quot;&quot;<br>        Convert transformed landmarks to MediaPipe protobuf format.<br>        <br>        Args:<br>            transformed_landmarks: List of transformed landmark tuples<br>            <br>        Returns:<br>            landmark_pb2.NormalizedLandmarkList: Protobuf representation of landmarks<br>        &quot;&quot;&quot;<br>        proto_landmarks = landmark_pb2.NormalizedLandmarkList()<br>        <br>        for pose_landmarks in transformed_landmarks:<br>            proto_landmarks.landmark.extend([<br>                landmark_pb2.NormalizedLandmark(<br>                    x=x, y=y, z=z, visibility=visibility, presence=presence<br>                ) for (x, y, z, visibility, presence) in pose_landmarks<br>            ])<br>        <br>        return proto_landmarks<br>    <br>    def reset_buffers(self):<br>        &quot;&quot;&quot;Reset all landmark buffers. Call this before processing a new video.&quot;&quot;&quot;<br>        self.landmark_buffers = self._init_buffers()<br>    <br>    def process_video(self, video_path: str) -&gt; landmark_pb2.NormalizedLandmarkList:<br>        &quot;&quot;&quot;<br>        Process an entire video file and extract pose landmarks with smoothing.<br>        <br>        Args:<br>            video_path: Path to the video file<br>            <br>        Returns:<br>            landmark_pb2.NormalizedLandmarkList: Protobuf containing all extracted landmarks<br>        &quot;&quot;&quot;<br>        self.reset_buffers()<br>        cap, fps, width, height = self._init_video_capture(video_path)<br>        frame_count = 0<br>        buffers = self._init_buffers()<br>        try:<br>            while cap.isOpened():<br>                success, image = cap.read()<br>                if not success:<br>                    break<br>                if(frame_count &gt; 20):<br>                    break<br>                timestamp_ms = int(cap.get(cv2.CAP_PROP_POS_MSEC))<br>                image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)<br>                                <br>                detection_result, mp_image = self._process_frame(image_rgb, timestamp_ms)                <br>                <br>                if detection_result.pose_landmarks:<br>                    transformed_points = self._transform_landmarks(detection_result.pose_landmarks, self.transform_func, buffers )<br>                    proto_landmarks = self._create_landmark_proto(transformed_points)<br>                frame_count += 1<br>        finally:<br>            cap.release()<br>        return proto_landmarks<br>    def get_all_landmarks(self):<br>        return self.global_pose_landmarks_list</pre><p>This is going to be a large file so brace yourselves. I implore you to understand what each function does. Take a look at the function call hierarchy to get a clear picture of how things are working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*F9ON3-U7YRawhCGsN-m23g.png" /></figure><p>While the Pose Landmarks Estimation Model does a great job at adding the landmarks, for our 3D models, or in any typical freely available 3D model, we have certain specifications, for example, the Make Human Project Specifications. Make Human project is a open source alternative to Unreal’s MetaHuman, and while Make Human Models are not as production ready for AAA game titles, it will do the job just fine for our task. For the purpose of mapping these pose landmarks to the actual 3D model, we add additional points to the landmarks array, using <em>add_extra_points </em>function:</p><pre>def add_extra_points(landmark_list):<br>    left_shoulder = landmark_list[11]<br>    right_shoulder = landmark_list[12]<br>    left_hip = landmark_list[23]<br>    right_hip = landmark_list[24]<br><br>    # We must use mean position of the left hip and right hip landmarks, since <br>    # in simple 3D models we have only one hip bone.<br>    hip = {<br>          &#39;x&#39;: (left_hip[&#39;x&#39;] + right_hip[&#39;x&#39;]) / 2.0,<br>          &#39;y&#39;: (left_hip[&#39;y&#39;] + right_hip[&#39;y&#39;]) / 2.0,<br>          &#39;z&#39;: (left_hip[&#39;z&#39;] + right_hip[&#39;z&#39;]) / 2.0,<br>          &#39;visibility&#39;: (left_hip[&#39;visibility&#39;] + right_hip[&#39;visibility&#39;]) / 2.0<br>        }<br>    landmark_list.append(hip)<br><br>    # The same mean position calculating tactics is done for spine<br>    spine = {<br>          &#39;x&#39;: (left_hip[&#39;x&#39;] + right_hip[&#39;x&#39;] + right_shoulder[&#39;x&#39;] + left_shoulder[&#39;x&#39;]) / 4.0,<br>          &#39;y&#39;: (left_hip[&#39;y&#39;] + right_hip[&#39;y&#39;] + right_shoulder[&#39;y&#39;] + left_shoulder[&#39;y&#39;]) / 4.0,<br>          &#39;z&#39;: (left_hip[&#39;z&#39;] + right_hip[&#39;z&#39;] + right_shoulder[&#39;z&#39;] + left_shoulder[&#39;z&#39;]) / 4.0,<br>          &#39;visibility&#39;: (left_hip[&#39;visibility&#39;] + right_hip[&#39;visibility&#39;] + right_shoulder[&#39;visibility&#39;] + left_shoulder[&#39;visibility&#39;]) / 4.0<br>        }<br>    landmark_list.append(spine)<br><br>    left_mouth = landmark_list[9]<br>    right_mouth = landmark_list[10]<br>    nose = landmark_list[0]<br>    left_ear = landmark_list[7]<br>    right_ear = landmark_list[8]<br>    # In simple 3D models, neck position is right <br>    # between the jaw(given by left mouth and right mouth)<br>    neck = {<br>          &#39;x&#39;: (left_mouth[&#39;x&#39;] + right_mouth[&#39;x&#39;] + right_shoulder[&#39;x&#39;] + left_shoulder[&#39;x&#39;]) / 4.0,<br>          &#39;y&#39;: (left_mouth[&#39;y&#39;] + right_mouth[&#39;y&#39;] + right_shoulder[&#39;y&#39;] + left_shoulder[&#39;y&#39;]) / 4.0,<br>          &#39;z&#39;: (left_mouth[&#39;z&#39;] + right_mouth[&#39;z&#39;] + right_shoulder[&#39;z&#39;] + left_shoulder[&#39;z&#39;]) / 4.0,<br>          &#39;visibility&#39;: (left_mouth[&#39;visibility&#39;] + right_mouth[&#39;visibility&#39;] + right_shoulder[&#39;visibility&#39;] + left_shoulder[&#39;visibility&#39;]) / 4.0<br>        }<br>    landmark_list.append(neck)<br><br>    # We have a single bone controlling head, so we must calculate<br>    # the average of nose and ears to get it&#39;s proper position.<br>    head = {<br>          &#39;x&#39;: (nose[&#39;x&#39;] + left_ear[&#39;x&#39;] + right_ear[&#39;x&#39;]) / 3.0,<br>          &#39;y&#39;: (nose[&#39;y&#39;] + left_ear[&#39;y&#39;] + right_ear[&#39;y&#39;]) / 3.0,<br>          &#39;z&#39;: (nose[&#39;z&#39;] + left_ear[&#39;z&#39;] + right_ear[&#39;z&#39;]) / 3.0,<br>          &#39;visibility&#39;: (nose[&#39;visibility&#39;] + left_ear[&#39;visibility&#39;] + right_ear[&#39;visibility&#39;]) / 3.0,<br>        }<br>    landmark_list.append(head)</pre><p>Next, let’s open up our <em>server.py </em>file and add a route called “/estimate-pose” which handles video uploads to this endpoint.</p><pre>from config import MODEL_PATH, VIDEO_OUT_PATH, VIDEO_PATH, SMA_WINDOW<br><br>from flask import Flask, request, jsonify<br>import uuid<br>import mimetypes<br>from threading import Thread<br>import cv2<br>from pose_estimator import getPoseEstimation<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/estimate-pose&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])<br>def estimate_pose():<br>    if &#39;video&#39; not in request.files:<br>        return jsonify({&#39;error&#39;: &quot;No video uploaded with key &#39;video&#39;&quot;}), 400<br>    video_file = request.files[&#39;video&#39;]<br>    video_path = f&quot;./uploads/{video_file.filename}&quot;<br>    video_file.save(video_path)<br><br>    # Process the video<br>    landmarks = getPoseEstimation()<br>    return jsonify({&quot;landmarks&quot;: landmarks})<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run(debug=True, host=&quot;0.0.0.0&quot;, port=5000)</pre><p>In this exploration of creating an API for pose estimation and 3D model manipulation, we have delved into the foundational steps necessary to build a pose estimation based application. From setting up the environment and defining the endpoints to implementing core functionalities like adding extra anatomical points, we’ve laid the groundwork for an application that leverages cutting-edge technology to enhance user experience in animation and interactive applications.</p><p>As we move forward, the potential for further improvements and integrations remains vast, opening doors to innovative solutions in real-time motion capture and animation. By harnessing the power of APIs, we can facilitate seamless communication between various components of our projects, driving the future of interactive technology and creative expression. As you continue to refine and expand your API, remember that the journey of development is as important as the final product. Embrace the challenges, iterate on your designs, and let your creativity guide you to new horizons.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d984b7f030f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>