Search code examples
androidandroid-layoutandroid-relativelayoutprogrammatically-created

Android Designing Layout programmatically


enter image description here

How can I make this layout in android programmatically.

I want just an idea not whole coding thing.


Solution

  • Here is the answer but not the direct answer. This is what I personally do to create complex layout programatically.

    Create the same layout in XML.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/some_big_image" />
    
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="#DD000000" >
    
        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:src="@drawable/ic_launcher" />
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/imageView2"
            android:layout_toRightOf="@+id/imageView2"
            android:text="TextView"
            android:textColor="@android:color/white" />
    
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/imageView2"
            android:layout_toRightOf="@+id/imageView2"
            android:text="TextView"
            android:textColor="@android:color/white" />
    </RelativeLayout>
    

    Now start from top parent to child.

        RelativeLayout mParent = new RelativeLayout(this);
        RelativeLayout.LayoutParams mParentParams = new RelativeLayout.LayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        mParent.setLayoutParams(mParentParams);
    
        ImageView mBigImageView = new ImageView(this);
        mBigImageView.setLayoutParams(mParentParams);
        mParent.addView(mBigImageView);
    

    As you practice you can directly code the same without creating xml.