Compose UI weird behavior (1)
On a new proof of the Pythagorean Theorem
In this article, I think the original idea can be converted to a pure Geometry solution. This way, any concern I have above are gone.
Forewords
Today, I read this post from the Hacker News, which leads me to this article (warning: paid Medium article) about a new proof of the Pythagorean Theorem that uses trigonometry.
It is said that proving the Pythagorean Theorem with trigonometry is impossible. I haven’t been involved in Math long enough to see where it is stated, but I can guess that it is because the idea of trigonometry is built on top of the perpendicular triangle, and many of its characteristic is derived from the theorem in question. For example, the famous fomular sin2(α)+cos2(α)=1sin^2(\alpha) + cos^2(\alpha) = 1sin2(α)+cos2(α)=1is a direct result of that theorem.
Reading through the article and the idea of the proof, I am amazed by the approach. It is indeed using the sin(α)sin(\alpha)sin(α) function, some of its characteristic, but in noway it requires the preconditions of the Pythagorean Theorem.
On one hand, I believe it is a correct and beautiful approach, and I’m so excited that given a very old and well-known problem with such a huge number of existing solutions, one can still find a new way to do it.
But on the other hand, from what I can read in the article, the approach includes the use of geometry series to calculate the sides of the big triangle. While it is possible, it requires some advance steps such as: (A) you need to explain the way you construct new triangles, prove that the new vertexes are all on the same line (which is the new edges), prove that it will be smaller and smaller and meet at a point, and (B) relying on the sum of an infinite series, which requires not only extra knowledge, but also more proofs (of the sum of the series) are needed.
It is hard to complaint a new proof of such a well-known problem. If I try to simplify the proof carelessly, I can easily make it another existing proof, and it is not the point. In this article, I think the original idea can be converted to a pure Geometry solution. This way, any concern I have above are gone.
- All of my acknowledge about the proof is from the article https://keith-mcnulty.medium.com/heres-how-two-new-orleans-teenagers-found-a-new-proof-of-the-pythagorean-theorem-b4f6e7e9ea2d.
- I don’t have any direct access to the original author of the proof, or their publishing as well.
- This article doesn’t try to take the credit of their idea. I only write it because I want to have a better version of it that fulfills my desire. I think the original idea is briliant.
Proving the Pythagorean Theorem
The Pythagorean Theorem
The square of the longest side (the hypotenuse, or c in the above diagram) is equal to the sum of the squares of the other two sides. So a2+b2=c2a² + b² = c²a2+b2=c2.
The proof
The original proof mentioned in the article above doesn’t solve the case where a=ba = ba=b. It cannot, because in that case, the 2 sides are parallel and their length become infinite.
By the way, that case is trivial: the triangle is a one-fourth of a square whose side length is ccc. The area of this square is c2c^2c2, while the triangle’s area is (ab)/2=a2/2(ab)/2 = a^2/2(ab)/2=a2/2. Therefore c2=4×a2/2=2a2=a2+b2c^2=4 \times a^2/2 = 2a^2 = a^2+b^2c2=4×a2/2=2a2=a2+b2, as desired.
When a≠ba≠ba=b : denote the vertixes of the triangles A,B,CA, B, CA,B,C and the side lengths are BC=a,CA=b,AB=cBC=a, CA=b, AB=cBC=a,CA=b,AB=c, we need to prove that c2=a2+b2c^2=a^2+b^2c2=a2+b2.
Let the angle ∠BAC=α,∠ABC=β\angle{BAC}=\alpha, \angle{ABC}=\beta∠BAC=α,∠ABC=β. WLOG, we can assume that α<β\alpha<\betaα<β.
Let DDD be the point on the line BCBCBC such that CCC is the midpoint of BDBDBD. We have △ABC=△ADC\triangle{ABC}=\triangle{ADC}△ABC=△ADC because they shares the same side ABABAB, the sides BC=DCBC=DCBC=DC and ∠ACB=∠ACD\angle{ACB}=\angle{ACD}∠ACB=∠ACD (they are equal to 90°90\degree90°). This gives us ∠BAC=∠DAC=α\angle{BAC}=\angle{DAC}=\alpha∠BAC=∠DAC=α or α1=α2=α\alpha_{1}=\alpha_{2}=\alphaα1=α2=α in the Figure B.
Since α<β\alpha<\betaα<β and α+β=90°\alpha+\beta=90\degreeα+β=90°then α<45°\alpha<45\degreeα<45°, and therefore ∠BAD<90°\angle{BAD}<90\degree∠BAD<90°, which means that if we draw a line (l)(l)(l) that is perpendicular to BABABA at BBB, (l)(l)(l) would never be parallel with the line (AD)(AD)(AD) and they cut each other at a point EEE like the Figure B.
Now, let FFF be the intersection of line (BE)(BE)(BE) and (AC)(AC)(AC)
Because of ∠BAC=∠EAC\angle{BAC}=\angle{EAC}∠BAC=∠EAC, ACACAC (or AFAFAF) is the bisector of ∠BAE\angle{BAE}∠BAE. With this, we have:
Now notice that △ABC\triangle{ABC}△ABC and △BFC\triangle{BFC}△BFC are similar because they share the same angle AAA, and they are both perpendicular triangles, therefore:
From (1)(1)(1) and (2)(2)(2):
Next, let DGDGDG be the altitude of △BDE\triangle{BDE}△BDE and BHBHBH be the altitude of △ABD\triangle{ABD}△ABD (see the Figure D below):
If S1S_{1}S1 is the area of △ABD\triangle{ABD}△ABD then 2S1=BH×AD=BD×AC2S_{1} = BH \times AD = BD \times AC2S1=BH×AD=BD×AC, i.e.,
Since ∠BGD=∠ABC=90°\angle{BGD}=\angle{ABC}=90\degree∠BGD=∠ABC=90° and ∠GBD=90°−∠ABD=∠BAC\angle{GBD}=90\degree-\angle{ABD}=\angle{BAC}∠GBD=90°−∠ABD=∠BAC, we have △GBD∼△CAB\triangle{GBD}\sim\triangle{CAB}△GBD∼△CAB, therefore:
(DB=2aDB=2aDB=2a because CCC is the midpoint of DBDBDB as we defined it, and CB=aCB=aCB=a).
If S2S_{2}S2 is the area of △BDE\triangle{BDE}△BDE then 2S2=DE×BH=BE×DG2S_{2} = DE \times BH = BE \times DG2S2=DE×BH=BE×DG, which gives us:
And since △ABC=△ADC\triangle{ABC}=\triangle{ADC}△ABC=△ADC (see above), we have AD=AB=cAD=AB=cAD=AB=c. Hence:
From (3)(3)(3) and (6)(6)(6), we have
Now, because △ABE\triangle{ABE}△ABE is a perpendicular triangle with ∠ABE=90°\angle{ABE}=90\degree∠ABE=90°, and BHBHBH is also an altitude of △ABE\triangle{ABE}△ABE, we have AB×BE=2S3=AE×BHAB \times BE = 2S_{3} = AE \times BHAB×BE=2S3=AE×BH where S3S_{3}S3 is the area of △ABE\triangle{ABE}△ABE. This equation gives us:
From (7)(7)(7) and (8)(8)(8), we have
Which is Q.E.DQ.E.DQ.E.D.
Cloning TikTok with Kohii
This tutorial shows you a way to build the full-screen vertical Video player like the TikTok application using the Kohii library.
This tutorial shows you a way to build the full-screen vertical Video player like the TikTok application using the Kohii library.
Source code
Source code: eneim/kohii-tutorial-301
Objective
Our objective is to replicate the Video playback UI of the TikTok application:
- Each video is played in full-screen, and the user can swipe the App vertically to switch to other videos.
- It starts playing the video automatically, if the user touches the video, it will pause/resume the video accordingly.
Requirement
You should go through some basic steps introduced in other tutorials before trying this one. Also, make sure you have the right to use the videos in your application.
Hands-on
Before we start, it’s worth noting that in this tutorial, we only replicate the video playback, but not try to implement other features like user profile, following, sharing, etc.
Step 1: Create new project
This step is the same as in this tutorial, but in this project, we will use the Bottom Navigation Activity template of Android Studio:
This is our project after step 1: kohii-tutorial-301/tree/step-1
Step 2: Adding dependencies
We will use ViewPager2 in this tutorial. It is the next version of the ViewPager as we knew, but way better. It supports vertical orientation which the ViewPager doesn’t, and it uses RecyclerView internally so it supports both Fragment (via the FragmentStateAdapter) and View (via the RecyclerView Adapter) which gives us a lot of flexibility.
dependencies { implementation fileTree(dir: "libs", include: ["*.jar"])++ def kohii_version = "1.1.0.2011003"+ implementation "im.ene.kohii:kohii-core:${kohii_version}"+ implementation "im.ene.kohii:kohii-exoplayer:${kohii_version}"+ implementation "com.google.android.exoplayer:exoplayer:2.11.3"++ implementation "androidx.viewpager2:viewpager2:1.0.0"+ implementation "org.jetbrains.kotlin:kotlin-stdlib:1.3.72" implementation 'androidx.core:core-ktx:1.3.0' implementation 'androidx.appcompat:appcompat:1.1.0'We also have a small update to remove obsolete usage of the ViewModelProviders
Here is our code after step 2: kohii-tutorial-301/tree/step-2
Step 3: Completing basic implementation
We reuse what has been done in the other tutorial to have a basic working implementation: kohii-tutorial-301/tree/step-3
In this step, I have some changes to the way we prepare data to simplify the implementations that don’t relate to Kohii usage. You should build your own data source in your application.
Step 4: Optimizing the UX
After step 3, our App looks like this →
As you can see, there are a lot of rooms for improvement:
- If user changes the tab of the Bottom Navigation Bar back and fort, the Fragment is recreated without any saved state. As a result, your list will restart from the first video after user switches the tab. It is not a thing that Kohii can help, but you need to do it by your own implementation.
- It takes a while before the playback starts. It is because by default, the player just starts loading the video when it is shown and plays it when it has enough buffer. Kohii provides you mechanism to customize this behavior. This tutorial will focus on this area.
Another thing we found in the TikTok app is that a video would repeat after it finishes. In this step 4, we will optimize the loading parameters of Kohii to archive 2 objectives:
- Video takes less time to start playing.
- Pre-load videos ahead so that it can start playing even earlier.
- Let the video repeat.
You can make it by 2 steps:
- First step is a setup for the ViewPager2: setting its off screen page limit to be non-default. By doing so, your ViewPager will bind some off-screen pages and keep it alive, but paused. This is the pre-condition for our pre-loading optimization:
pager.offscreenPageLimit = 1- Let Kohii pre-load the video. At the same time we can set the repeat options like below:
class HomeAdapter(@@ -21,6 +22,8 @@ val videoItem = VideoItem(position = position) kohii.setUp(videoItem.videoUrl) { tag = "${videoItem.videoUrl}+${position}"+ preload = true+ repeatMode = Common.REPEAT_MODE_ONE }.bind(holder.playerView) } }After these steps, we are closer to the target, but the videos still take time for the loading. The next things we do are advance usages of Kohii, but once you are familiar with it, it will be a powerful tool for your need: customizing the Kohii instance and using MemoryMode to improve the playback UX.
By default, Kohii wraps the ExoPlayer implementation with default parameters. These parameters affect how much time it takes a player to load the resource before it starts rendering the video. Depending on the video we play, we can adjust them to meet our requirement. For example, if your videos are high-quality movies (e.g. Netflix videos), you may want to buffer more content before the first rendering, so that it always has enough buffer to keep the playback smooth. In the case of TikTok’s videos, they are generally short and light-weight, we can shorten the loading time to start playing the video quickly.
The snippet below shows you how to construct a singleton instance of Kohii that use custom parameters to shorten the loading time by a factor of 10:
val kohii = createKohii( requireContext(), ExoPlayerConfig( minBufferMs = DEFAULT_MIN_BUFFER_MS / 10, maxBufferMs = DEFAULT_MAX_BUFFER_MS / 10, bufferForPlaybackMs = DEFAULT_BUFFER_FOR_PLAYBACK_MS / 10, bufferForPlaybackAfterRebufferMs = DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS / 10 ))createKohii is an extension method to help you build a custom instance of Kohii quickly. Kohii recommends you use its instance as a singleton. Because that way, all the resources can be reused and passed around for multiple components. The snippet below is one way to use the Capsule helper class in the library to build a singleton easily:
// A singleton holderobject KohiiProvider { private val capsule = Capsule<Kohii, Context>(creator = { context -> createKohii(context, ExoPlayerConfig.FAST_START) }) fun get(context: Context): Kohii = capsule.get(context)}// Obtain the Kohii singleton laterval kohii = KohiiProvider.get(context)Now about using MemoryMode, this class is another useful feature of Kohii: It allows the client to decide how much memory it allows the library to use for the playback. At the same time, it follows the system’s callback so that regardless of the configuration you made, if the system runs out of memory, Kohii will release the resource it uses to gain back the performance. You need to remember that, using more memory can have better UX, but it also increases GC count, consumes more energy so it may impact your app’s performance.
The usage is simple. In this tutorial, we want to allow it to use higher memory than usual, so that the next and previous video can stay in the memory and be able to resume as soon as possible:
- kohii.register(this).addBucket(pager)+ kohii.register(this, memoryMode = HIGH)+ .addBucket(pager)With this setup, you allow more videos to be cached after it is paused. Let’s take a look at our app before and after the changes:
As you can see, the playback performance was significantly improved.
Below is the source code of our project after this step: kohii-tutorial-301/tree/step-4
Step 5: User interaction
This step will add the following behavior to the App: if the user clicks a video while it is playing, the video will be paused, and if it is already paused by another click, it will be resumed. This behavior requires a setup to enable the manual playback controller that is discussed in this tutorial. But unlike that tutorial where we use the PlayerView’s PlayerControlView for the playback controller, we only need to handle the click event here. To do so, we need to use a custom Controller like below:
kohii.setUp(videoItem.videoUrl) { tag = "${videoItem.videoUrl}+${position}" preload = true repeatMode = Common.REPEAT_MODE_ONE+ controller = object : Controller {+ override fun kohiiCanStart(): Boolean = true+ override fun kohiiCanPause(): Boolean = true+ override fun setupRenderer(playback: Playback, renderer: Any?) {+ holder.playerContainer.setOnClickListener {+ val playable = playback.playable ?: return@setOnClickListener+ if (playable.isPlaying()) {+ playback.manager.pause(playable)+ } else {+ playback.manager.play(playable)+ }+ }+ }++ override fun teardownRenderer(playback: Playback, renderer: Any?) {+ holder.playerContainer.setOnClickListener(null)+ }+ } }.bind(holder.playerView) } }Here we have another field for the ViewHolder called playerContainer. The reason is PlayerView may intercept the click event, so we wrap it by a FrameLayout and let this layout to receive the click of the user:
<?xml version="1.0" encoding="utf-8"?><!-- Please check the full source code in the repository. --><FrameLayout android:clickable="true" android:focusable="true" > <com.google.android.exoplayer2.ui.PlayerView /></FrameLayout>After this step, our App is closer to our objective now →
And here is the source code of our project at this step: kohii-tutorial-301/tree/step-5
Wrap-up
In this tutorial, we learn how to use Kohii to build a replica of the TikTok’s video player. With some optimizations, you can see our app could perform very well. In the real-life scenario, it also relies heavily on your server implementation. So keep in mind that, while Kohii cannot do all the work for you, it can be really useful in the specific scenarios.
If you want to learn more about how to use Kohii, please take a look here:
Last but not least
Kohii is an open source project I build after work. It has been under development for nearly 2 years and I’m improving it everyday. If you are using Kohii and finding it useful for your work, you can send me some help either by staring the repository or/and buying me a cup of coffee at my sponsor page. Your help is always appreciated.
Thanks for using Kohii and happy coding.




