Issue
I'm trying to draw a cigarette with the "ash" view being a percentage of the "smokeable" view. It needs to be a percentage because I am going to use a slider which will change the percentage of the "ash" view.
Here is what I want:

Here is my code:
<LinearLayout
android:id="@+id/cigarette"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginBottom="20dp"
android:orientation="horizontal">
<View
android:id="@+id/butt"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".25"
android:background="#ff7700" />
<LinearLayout
android:id="@+id/smokeable"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".75"
android:background="#cccccc"
android:orientation="horizontal">
<View
android:id="@+id/ash"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".33"
android:background="#777777"
android:gravity="right" />
</LinearLayout>
</LinearLayout>
In this example I want the ash to be 33% of the smokeable view. I can't figure out why this isn't working. Any help would be appreciated.
Solution
The inner LinearLayout needs another child View for the not-yet-consumed part of the cigarette. Its layout_weight has to be 1 - 0.33 = 0.67 in your example (the sum of the weights of both siblings always has to be 1).
<LinearLayout
android:id="@+id/cigarette"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_below="@+id/titleText"
android:orientation="horizontal">
<View
android:id="@+id/butt"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".25"
android:background="#ff7700" />
<LinearLayout
android:id="@+id/smokeable"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".75"
android:orientation="horizontal">
<View
android:id="@+id/rest"
android:layout_width="0dp"
android:layout_height="match_parent"
android:background="#cccccc"
android:layout_weight=".67"
/>
<View
android:id="@+id/ash"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".33"
android:background="#777777"
android:gravity="right" />
</LinearLayout>
</LinearLayout>
Please note that while this will fix your code, the "nested weighted LinearLayout" approach isn't a good way to go, even if modern devices should not run into performance problems.
The solution by lelloman involving a custom View is much better because you need only one View, not two ViewGroups plus three Views. You have one method to easily change the percentage, plus all the calculating and drawing parts are nicely encapsulated.
Answered By - Bö macht Blau
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.