Jemil Riahi Jemil Riahi - 4 days ago 4
Android Question

Layout weight not working as intended

I have a slight problem getting my

layout_weight
to work. I am creating a custom bottomBar. But i cant make it to stretch as i want it to.

Bottom Bar View

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/bottom_bar_root"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:id="@+id/bottom_bar_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="4"
android:orientation="horizontal"/>
</RelativeLayout>


This is the big container i am adding my buttons (items) to.

Bottom Bar Item

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<android.support.v7.widget.AppCompatImageView
android:id="@+id/bottom_bar_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/arrow_up_float"/>
<TextView
android:id="@+id/bottom_bar_item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEXT"/>
</LinearLayout>


This is my items that i add dynamically to the view. But somehow the view is not stretched properly.

But when i hardcode it in. It works. So could it be that layout weight does not work dynamically?

How i add the views (items)

private void updateItems(final List<BottomBarTab> bottomBarTabs) {
if (bottomBarTabs.size() < TABS_COUNT) {
throw new RuntimeException("Not enough buttons for bottomBar");
}

for (int i = 0; i < TABS_COUNT; i++) {
bottomBarTabs.get(i).setOnClickListener(this);

bottomBarTabs.get(i).prepareLayout();
container.addView(bottomBarTabs.get(i));
}
}


Screenshot

enter image description here

Answer
public void prepareLayout() {
    View view = inflate(getContext(), R.layout.bottom_bar_item,this);

    LinearLayout.LayoutParams params =
            new LayoutParams(0,LayoutParams.MATCH_PARENT,LAYOUT_WEIGHT);

    view.setLayoutParams(params);


    if(backgroundColor != null) {
        view.setBackgroundColor(backgroundColor);
    }

    TextView titleText = (TextView) view.findViewById(R.id.bottom_bar_item_text);
    titleText.setText(title);

    AppCompatImageView imageView = (AppCompatImageView) view.findViewById(R.id.bottom_bar_item_icon);
    imageView.setImageResource(iconResId);
}

I changed in my prepareLayout function and put new layoutParams. Because somehow after inflation. The view ignores the weight that was set to it. So i had to force it by code. Maybe this is a android bug?

Comments