Reputation: 8128
When I use statically defined layout, I'm able to do this by setting wrap_content
as LinearLayout
layout_width
and match_parent
as its childrens' layout_width
.
For example, the following XML layout definition:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#f88"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#8f8"
android:text="Smaller"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#8f8"
android:text="I'm a bigger view"
/>
</LinearLayout>
looks like the following (note that you can't see LinearLayout background color as it's obscured by TextViews completely):
Which is the desired result. But if I use the same technique when inflating and adding views dynamically via LayoutInflater, the LinearLayout gets stretched to screen width.
(by using LayoutInflater I mean using this method and I pass the right value for root
argument)
Why this happens? How can I make similar thing dynamically then? Is it possible to define that in XML, or I'm doomed to implement that logic by myself?
I display the layout in a PopupWindow. When I look at the LinearLayout in Hierarchy Viewer, it has layout_width
= match_parent
, which is very strange, because it's wrap_content
in my XML.
The problem was caused by adding another View
with match_parent
width. (it's used as divider) Like this:
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#777" />
Seems like it has no concept of "required width" and forces its parent to stretch.
Upvotes: 1
Views: 96
Reputation: 8128
Problem is solved by simply changing view class of "divider" from View
to TextView
. The latter doesn't try to grab all available space. But it's still interesting if there are more elegant solutions (I suspect that using TextView for this purpose is overkill and isn't very efficient).
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#777" />
Upvotes: 0