Reputation: 135
I would just like to know if every time I need to set the View's size (width or/and height) as a function of its parent size (e.g. width = 0.5 * parent_size), I have to create a custom View and override onMeasure() or is there a way to do it using XML? Thank you in advance!
Edit:
What I'd like to achieve is something like : place a view left aligned, with a width equals to 1/10th of the parent width and a height equals to 1/5th of the parent height. So on for other Views.
Upvotes: 0
Views: 78
Reputation: 3263
Here is an answer with two nested LinearLayouts and a TextView in the upper left corner, the TextView is 10% of width and 10% of height. Just to prove it works with only one view.
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:weightSum="10"
android:background="#FF0000"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="0dp"
android:orientation="vertical"
android:weightSum="10"
android:background="#00FF00"
android:layout_weight="1"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#000000"
android:layout_weight="1"
android:text="Hello"
android:textColor="#FFFFFF"
/>
</LinearLayout>
</LinearLayout>
Upvotes: 1
Reputation: 1800
you can use LinearLayout as a container and android:layout weight attribute for example. You can read more here: developer.android.com/guide/topics/ui/layout/linear.html#Weight
So, if you want to add only one element, you can add your view with weight=1 and one element with weight=9. But if you want to add 10 view in one row (1/10 of height for each) - you can use GridView for that or TableLayout.
Upvotes: 0
Reputation: 7881
I have to create a custom View and override
onMeasure()
or is there a way to do it using XML?
There are no such way to achieve you goal using XML Layout file.
You have to manage this view dynamically .Your second approach is right approach .
You need to create dynamic view and make onMeasure()
method according to your functions.
Upvotes: 0