Search code examples
androidxmlandroid-layoutandroid-inflateandroid-adapterview

How to let an image define the layout's with in Android


I want an image to define the layout's bounds and need all other elemets to oriente themselfes to it.

Screenshot

My problem here is that i want the text to wrap, when it reaches the images end. Any idea how to solve this via layout xml or do I have to implement that via code?

My current layout looks like this:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/KHFGreen"
        android:padding="3dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:layout_gravity="left|center_vertical">

        <ImageView
            android:id="@+id/icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/five"
            android:scaleType="fitCenter"
            android:adjustViewBounds="true" />

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:text="Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore. "
            android:layout_gravity="left|center_vertical"
            android:nestedScrollingEnabled="false" />

    </FrameLayout>
</FrameLayout>

Many thanks!


Solution

  • add below logic in oncreate method.

    imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    
        @Override
        public void onGlobalLayout() {
    
            textView.getLayoutParams().width = imageView.getMeasuredWidth();
    
            if (Build.VERSION.SDK_INT >= 16) {
                imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } else {
                imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        }
    });
    

    enter image description here

    When I removed android:nestedScrollingEnabled="false" and tried I got what u asked and I am not able to add android:nestedScrollingEnabled="false" also, "error: No resource identifier found for attribute 'nestedScrollingEnabled' in package 'android'"

    enter image description here