<?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 Hamed Sj on Medium]]></title>
        <description><![CDATA[Stories by Hamed Sj on Medium]]></description>
        <link>https://medium.com/@hamedsj5?source=rss-84ecf29f3a83------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oTGQpUkE9MccrkTjryKXtg.jpeg</url>
            <title>Stories by Hamed Sj on Medium</title>
            <link>https://medium.com/@hamedsj5?source=rss-84ecf29f3a83------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:25:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamedsj5/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[CustomLayoutManager? easy-peasy]]></title>
            <link>https://medium.com/@hamedsj5/customlayoutmanager-easy-peasy-7e4730eb3439?source=rss-84ecf29f3a83------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e4730eb3439</guid>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[layoutmanager]]></category>
            <dc:creator><![CDATA[Hamed Sj]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 19:58:42 GMT</pubDate>
            <atom:updated>2023-06-06T10:19:21.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1AelCzFDEFH4qYUwtwyydw.jpeg" /><figcaption>This image is only for design and we want just create a simple linear layout manager in this blog post =) After reading this post you can do that by yourself. also you can find this sample project link in the end of this post.</figcaption></figure><p>It was hard for me to understand how the layout manager works alongside the recycler view and how can I write my layout manager with specific motions or paths to scroll.<br><a href="https://youtu.be/W55PSgzH6HI">This video</a> on youtube from Polly McEldowney helped me a lot. So I decided to make it easier for someone like me to learn the very first steps of creating a layout manager.</p><h3>What is the layout manager?</h3><p>A <em>LayoutManager</em> is an abstract class that according to the Java doc above the definition of it:</p><blockquote>A <em>LayoutManager</em> is responsible for measuring and positioning item views within a <em>RecyclerView</em> as well as determining the policy for when to recycle item views that are no longer visible to the user.</blockquote><p>Therefore, when we want to write our own LayoutManager we should measure and position the child and we are responsible for what happens when the user scrolls the RecyclerView (We should remeasure and reposition them).</p><h3>Basic methods</h3><ul><li><strong><em>generateDefaultLayoutParams:</em></strong></li></ul><p>As you probably understood from its name, This method is responsible for generating a <em>RecyclerView.LayoutParams</em> for children of the RecyclerView. You can make all the children of the RecyclerView match their parents for example.<br>but if you want the item view to decide about its size and other layout parameters you can simply implement it like this:</p><pre>override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams =<br>    RecyclerView.LayoutParams(<br>        RecyclerView.LayoutParams.WRAP_CONTENT,<br>        RecyclerView.LayoutParams.WRAP_CONTENT<br>    )</pre><ul><li><strong><em>onLayoutChildren:</em></strong></li></ul><p>The main responsibility of this method is to measure and lay out the children of the RecyclerView based on their position.<br>It also has some other responsibilities like animating the items that we do not cover in this blog post.<br>So what is measurement? To set the width and height of a view.<br>And what does it mean to lay out a view? To set the exact position of a view on the screen.<br>First, let us see what happens if we just measure and layout the first child of the RecyclerView:</p><pre>override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State?) {<br>    if (itemCount == 0) return<br>    val view = recycler.getViewForPosition(0)<br>    addView(view)<br><br>    val layoutParams = view.layoutParams as RecyclerView.LayoutParams<br>    layoutParams.width = width<br>    layoutParams.height = width // square item<br>    view.layoutParams = layoutParams<br><br>    var left = 0<br>    var right = left + width<br>    var top = 0<br>    var bottom = top + width<br>    measureChild(view, width, width) //  square item<br>    layoutDecorated(view, left, top, right, bottom)<br>}</pre><p>And the result will be:</p><figure><img alt="A screenshot from the android emulator with only one square item in the beginning of the screen" src="https://cdn-images-1.medium.com/max/1024/1*v9toEUJ-2Odyz-geXSTH6g.jpeg" /></figure><p>The next step is to consider the index of items in the process of layout them. To do that we should change their <strong><em>top</em></strong> position. we know that the <em>i</em>th item should be <em>(i-1) * height </em>pixels far away from the top. so we can change the definition of <strong><em>onLayoutChildren</em></strong> like this:</p><pre>override fun onLayoutChildren(<br>    recycler: RecyclerView.Recycler,<br>    state: RecyclerView.State?<br>) {<br>    if (itemCount == 0) return<br>    for (position in 0 until itemCount) {<br>        val view = recycler.getViewForPosition(position)<br>        addView(view)<br><br>        val layoutParams = view.layoutParams as RecyclerView.LayoutParams<br>        layoutParams.width = width<br>        layoutParams.height = width // square item<br>        view.layoutParams = layoutParams<br><br>        var left = 0<br>        var right = left + width<br>        var top = position * width // width of our item is equal to its height<br>        var bottom = top + width<br>        measureChild(view, width, width) //  square item<br>        layoutDecorated(view, left, top, right, bottom)<br>    }<br>}</pre><p>As you can see, We added a <strong><em>for</em></strong> loop To measure and layout all the children and then we added a position factor in the definition of the <strong><em>top</em></strong> variable.<br>The result will be like this (remember that we do not support scrolling with our layout manager yet):</p><figure><img alt="A screenshot from the android emulator with a list of square items" src="https://cdn-images-1.medium.com/max/1024/1*gMR2n57LFioZcFHbp9J_dA.jpeg" /></figure><p>Now we can go for supporting scroll with our layout manager.</p><ul><li><strong>canScrollVertically </strong>or<strong> <em>canScrollHorizontally:</em></strong></li></ul><p>As you can find out from their name, these methods determine whether our layout manager supports vertical/horizontal scrolling or not. For our case, we can simply use it like this:</p><pre>override fun canScrollVertically(): Boolean {<br>    return true<br>}</pre><ul><li><strong><em>scrollVerticallyBy</em></strong> or <strong><em>scrollHorizontallyBy:</em></strong></li></ul><p>These are the promised methods that we can handle the vertical/horizontal scroll within them. A parameter named <strong><em>dy</em></strong> or <strong><em>dx </em></strong>passed to these methods enables us to find the distance of the scroll. In this method, we should measure and layout the children of the RecyclerView again. And we need to take the <strong><em>dx</em></strong> or <strong><em>dy</em></strong> distance into account when we want to remeasure and relayout them. To do that, we can sum up all the current body of <strong><em>onLayoutChildren</em></strong> into a method named <strong><em>fill</em></strong> like this:</p><pre>private fun fill(recycler: Recycler) {<br>    if (itemCount == 0) return<br>    for (position in 0 until itemCount) {<br>        val view = recycler.getViewForPosition(position)<br>        addView(view)<br><br>        val layoutParams = view.layoutParams as RecyclerView.LayoutParams<br>        layoutParams.width = width<br>        layoutParams.height = width // square item<br>        view.layoutParams = layoutParams<br><br>        var left = 0<br>        var right = left + width<br>        var top = position * width - offset // we take &#39;offset&#39; into account<br>        var bottom = top + width<br>        measureChild(view, width, width) //  square item<br>        layoutDecorated(view, left, top, right, bottom)<br>    }<br>}</pre><p>As you can see we took a variable named offset into account in the definition of the <strong><em>top</em></strong> variable. The initial value of <strong><em>offset</em></strong> is zero, But in every call of <strong><em>scrollVerticallyBy</em></strong>/<strong><em>scrollHorizontallyBy</em></strong>, we update it.<br>Now we can simply define our <strong><em>scrollVerticallyBy</em></strong> like this:</p><pre>override fun scrollVerticallyBy(<br>    dy: Int,<br>    recycler: Recycler?,<br>    state: RecyclerView.State?<br>): Int {<br>    if (itemCount == 0) return 0<br>    val lastOffset = offset<br>    offset += dy<br>    return lastOffset - offset<br>}</pre><h3>Two things that we missed</h3><ol><li><strong><em>Boundaries of scolling</em></strong></li></ol><p>We need to prevent the scrolling behind the first and last items of the RecyclerView to do that we can simply control the updating of the offset in the <strong><em>scrollVerticallyBy</em></strong>/<strong><em>scrollHorizontallyBy </em></strong>methods. To do this, we can change these methods like:</p><pre>override fun scrollVerticallyBy(<br>    dy: Int,<br>    recycler: Recycler?,<br>    state: RecyclerView.State?<br>): Int {<br>    if (itemCount == 0) return 0<br>    val lastOffset = offset<br>    val firstItem = requireNotNull(getChildAt(0))<br>    val lastItem = requireNotNull(getChildAt(itemCount - 1))<br>    val startOfFirstItem = getDecoratedTop(firstItem)<br>    val endOfLastItem = getDecoratedBottom(lastItem)<br>    offset = min(max(startOfFirstItem, offset + dy), offset + endOfLastItem - height)<br>    return lastOffset - offset<br>}</pre><p>This combination of <strong><em>min</em></strong> and <strong><em>max</em></strong> methods in updating offset used for preventing the <strong><em>offset</em></strong> to be less or more than what it should be.</p><p>2. <strong><em>Recycling the views that are out of sight</em></strong></p><p>Yes, You are responsible to notify the RecyclerView to recycle the views that are out of sight. but where should you do that? Yes in the <strong><em>fill</em></strong> method.<br>Before measuring and layouting the first view in this method we should temporarily detach the cached views from the RecyclerView and then after measuring and layouting all the children we should recycle all the new children in the scrap list. we can simply do these by changing the <strong><em>fill</em></strong> method like this:</p><pre>private fun fill(recycler: Recycler) {<br>    if (itemCount == 0) return<br>    detachAndScrapAttachedViews(recycler)<br>    for (position in 0 until itemCount) {<br>        val view = recycler.getViewForPosition(position)<br>        addView(view)<br><br>        val layoutParams = view.layoutParams as RecyclerView.LayoutParams<br>        layoutParams.width = width<br>        layoutParams.height = width<br>        view.layoutParams = layoutParams<br><br>        var left = 0<br>        var right = left + width<br>        var top = position * width - offset<br>        var bottom = top + width<br>        measureChild(view, width, width)<br>        layoutDecorated(view, left, top, right, bottom)<br>    }<br>    val scrapListCopy = recycler.scrapList.toList()<br>    scrapListCopy.forEach {<br>        recycler.recycleView(it.itemView)<br>    }<br>}</pre><p>As you can see we called the <strong><em>detachAndScrapAttachedViews </em></strong>before the for loop in order to detach the attached views, And we called <strong><em>recycleView</em></strong> for all the items of the scrap list in the recycler.</p><p>You can find the whole code together in <a href="https://gist.github.com/hamedsj/727aad238e9886bd01d1cc86f1e746fd">this gist</a>.<br>Also you can find a completed sample project <a href="https://github.com/hamedsj/GridChallenge">here on my github</a> (It’s related to cover of this blog post)</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e4730eb3439" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a custom middleware for Django project]]></title>
            <link>https://medium.com/@hamedsj5/create-a-custom-middleware-for-django-project-f0806bf36726?source=rss-84ecf29f3a83------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0806bf36726</guid>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Hamed Sj]]></dc:creator>
            <pubDate>Sun, 03 May 2020 18:49:27 GMT</pubDate>
            <atom:updated>2020-05-03T18:49:27.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*mXHklAWK0o1li1aVnMsYOQ.png" /></figure><p><strong>What are middlewares?<br></strong>Let’s start simple. In short, middlewares are classes that contain some functions called before and after all view functions. For more detail on middleware, you can click <a href="https://medium.com/zeitcode/django-middlewares-and-the-request-response-cycle-fcbf8efb903f">here</a>.</p><p><strong>What requirements should middlewares have?<br></strong>the only requirement for a class to be a middleware is that middleware must have at least one of the following methods:<br><em>process_request </em>,<em>process_view</em>, <em>process_response</em>, <em>process_exception</em></p><p><strong>How do these methods work?<br></strong>Every Django project has a list called MIDDLEWARES (or MIDDLEWARE_CLASSES in older versions) in settings.py that contains the path of every middleware that has at least one of the methods mentioned above.<br>after request received by the framework, WSGI Handler builds a HttpRequest object for passing to view functions and in this process it iterates through the list and it will call process_request method from every class in the list that contains this method. (if one class in the list doesn’t have process_request , it will just get skipped.)<br>after building HttpRequest object and before passing it to every view function WSGI Handler will call process_view method of middlewares.</p><blockquote><em>process_request</em> and <em>process_view</em> methods should return <em>None</em> that in this case WSGI Handler will continue the cycle; or this methods should alternatively return<em> HttpResponse</em> that in this case WSGI Handler will begin <em>process_response</em> cycle.</blockquote><p>if a view function raise an exception WSGI Handler will begin process_exception cycle and if a view function returns HttpResponse object, WSGI Handler will begin process_response cycle.</p><blockquote>unlike <em>process_request</em> and <em>process_view</em> methods, <em>process_response</em> and <em>process_exception</em> can only modify the data of response/exception</blockquote><p><strong>Let’s write some code</strong></p><p>At first, we initialize a django project with the following file tree:</p><pre>├── mysite<br>│   ├── manage.py<br>│   └── mysite   <br>│       ├── __init__.py <br>│       ├── settings.py<br>│       ├── urls.py<br>│       └── wsgi.py<br>└── myapp   <br>    │   ├── __init__.py <br>    │   ├── admin.py<br>    │   ├── apps.py<br>    │   ├── models.py<br>    │   ├── MyMiddleware.py<br>    │   ├── tests.py<br>    │   ├── urls.py<br>    └   └── views.py</pre><p>we define two views; one of them for testing process_request and another for process_view test :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43ecdf4fc24ec1b1add29ded44c4ecc4/href">https://medium.com/media/43ecdf4fc24ec1b1add29ded44c4ecc4/href</a></iframe><p>we change mysite/urls.py contents to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/073efbe7703ec1f98877765ea87a663a/href">https://medium.com/media/073efbe7703ec1f98877765ea87a663a/href</a></iframe><p>and after that, we change myapp/urls.py to have two views that mentioned above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8af8a027c9319df588581a2dde25d2c/href">https://medium.com/media/e8af8a027c9319df588581a2dde25d2c/href</a></iframe><p>now it’s time to write our custom middleware in myapp/MyMiddlware.py file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/192891ceb08eb91f5519bef2d6a1f150/href">https://medium.com/media/192891ceb08eb91f5519bef2d6a1f150/href</a></iframe><p>as you can see we inherit MyMd class from MiddlewareMixin class.<br>MiddlewareMixin is a tool that turns deprecated Middlewares into new ones.<br>if any request had a parameter in its GET request named p our middleware will return “Hello World =)”<br>and if a request was sent to process_view_test function and doesn’t have p parameter then our middleware will return “This method only work for this view =)”</p><p>and in the end, we should add our middleware to MIDDLEWARE list in settings.py like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f5efc0a195212e7ac8fee5f94575d2a/href">https://medium.com/media/7f5efc0a195212e7ac8fee5f94575d2a/href</a></iframe><p><strong>Test the result</strong></p><p>Test 0 : curl <a href="http://127.0.0.1:8000/myview/">http://127.0.0.1:8000/myview/</a> <br>Output : Hello There =)</p><p>Test 1 : curl <a href="http://127.0.0.1:8000/myview/?p=2">http://127.0.0.1:8000/myview/?p=2</a> <br>Output : Hello World=)</p><p>Test 2 : curl <a href="http://127.0.0.1:8000/process_view_test/">http://127.0.0.1:8000/process_view_test/</a> <br>Output : This method only work for this view =)</p><p>Test 3 : curl <a href="http://127.0.0.1:8000/process_view_test/?p=1">http://127.0.0.1:8000/process_view_test/?p=1</a> <br>Output : Hello World=)</p><p>The source code of this blog is available in <a href="https://github.com/hamedsj/django-custom-middleware">this Github repository</a>.</p><p>It’s my very first time writing in medium, I’d be glad if you help me with your support and comments.<br>Thank you for reading my post =))</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0806bf36726" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>