Create a custom View by inflating a layout?












75















I am trying to create a custom View that would replace a certain layout that I use at multiple places, but I am struggling to do so.



Basically, I want to replace this:



<RelativeLayout
android:id="@+id/dolphinLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/background_box_light_blue"
android:padding="10dip"
android:layout_margin="10dip">
<TextView
android:id="@+id/dolphinTitle"
android:layout_width="200dip"
android:layout_height="100dip"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dip"
android:text="@string/my_title"
android:textSize="30dip"
android:textStyle="bold"
android:textColor="#2E4C71"
android:gravity="center"/>
<Button
android:id="@+id/dolphinMinusButton"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_toRightOf="@+id/dolphinTitle"
android:layout_marginLeft="30dip"
android:text="@string/minus_button"
android:textSize="70dip"
android:textStyle="bold"
android:gravity="center"
android:layout_marginTop="1dip"
android:background="@drawable/button_blue_square_selector"
android:textColor="#FFFFFF"
android:onClick="onClick"/>
<TextView
android:id="@+id/dolphinValue"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_marginLeft="15dip"
android:background="@android:drawable/editbox_background"
android:layout_toRightOf="@+id/dolphinMinusButton"
android:text="0"
android:textColor="#2E4C71"
android:textSize="50dip"
android:gravity="center"
android:textStyle="bold"
android:inputType="none"/>
<Button
android:id="@+id/dolphinPlusButton"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_toRightOf="@+id/dolphinValue"
android:layout_marginLeft="15dip"
android:text="@string/plus_button"
android:textSize="70dip"
android:textStyle="bold"
android:gravity="center"
android:layout_marginTop="1dip"
android:background="@drawable/button_blue_square_selector"
android:textColor="#FFFFFF"
android:onClick="onClick"/>
</RelativeLayout>


By this:



<view class="com.example.MyQuantityBox"
android:id="@+id/dolphinBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:myCustomAttribute="@string/my_title"/>


So, I do not want a custom layout, I want a custom View (it should not be possible for this view to have child).



The only thing that could change from one instance of a MyQuantityBox to another is the title. I would very much like to be able to specify this in the XML (as I do on the last XML line)



How can I do this? Should I put the RelativeLayout in a XML file in /res/layout and inflate it in my MyBoxQuantity class? If yes how do I do so?



Thanks!










share|improve this question























  • See "Compound Controls" in Android, and this link: stackoverflow.com/questions/1476371/…

    – greg7gkb
    Aug 9 '12 at 20:26
















75















I am trying to create a custom View that would replace a certain layout that I use at multiple places, but I am struggling to do so.



Basically, I want to replace this:



<RelativeLayout
android:id="@+id/dolphinLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/background_box_light_blue"
android:padding="10dip"
android:layout_margin="10dip">
<TextView
android:id="@+id/dolphinTitle"
android:layout_width="200dip"
android:layout_height="100dip"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dip"
android:text="@string/my_title"
android:textSize="30dip"
android:textStyle="bold"
android:textColor="#2E4C71"
android:gravity="center"/>
<Button
android:id="@+id/dolphinMinusButton"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_toRightOf="@+id/dolphinTitle"
android:layout_marginLeft="30dip"
android:text="@string/minus_button"
android:textSize="70dip"
android:textStyle="bold"
android:gravity="center"
android:layout_marginTop="1dip"
android:background="@drawable/button_blue_square_selector"
android:textColor="#FFFFFF"
android:onClick="onClick"/>
<TextView
android:id="@+id/dolphinValue"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_marginLeft="15dip"
android:background="@android:drawable/editbox_background"
android:layout_toRightOf="@+id/dolphinMinusButton"
android:text="0"
android:textColor="#2E4C71"
android:textSize="50dip"
android:gravity="center"
android:textStyle="bold"
android:inputType="none"/>
<Button
android:id="@+id/dolphinPlusButton"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_toRightOf="@+id/dolphinValue"
android:layout_marginLeft="15dip"
android:text="@string/plus_button"
android:textSize="70dip"
android:textStyle="bold"
android:gravity="center"
android:layout_marginTop="1dip"
android:background="@drawable/button_blue_square_selector"
android:textColor="#FFFFFF"
android:onClick="onClick"/>
</RelativeLayout>


By this:



<view class="com.example.MyQuantityBox"
android:id="@+id/dolphinBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:myCustomAttribute="@string/my_title"/>


So, I do not want a custom layout, I want a custom View (it should not be possible for this view to have child).



The only thing that could change from one instance of a MyQuantityBox to another is the title. I would very much like to be able to specify this in the XML (as I do on the last XML line)



How can I do this? Should I put the RelativeLayout in a XML file in /res/layout and inflate it in my MyBoxQuantity class? If yes how do I do so?



Thanks!










share|improve this question























  • See "Compound Controls" in Android, and this link: stackoverflow.com/questions/1476371/…

    – greg7gkb
    Aug 9 '12 at 20:26














75












75








75


13






I am trying to create a custom View that would replace a certain layout that I use at multiple places, but I am struggling to do so.



Basically, I want to replace this:



<RelativeLayout
android:id="@+id/dolphinLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/background_box_light_blue"
android:padding="10dip"
android:layout_margin="10dip">
<TextView
android:id="@+id/dolphinTitle"
android:layout_width="200dip"
android:layout_height="100dip"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dip"
android:text="@string/my_title"
android:textSize="30dip"
android:textStyle="bold"
android:textColor="#2E4C71"
android:gravity="center"/>
<Button
android:id="@+id/dolphinMinusButton"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_toRightOf="@+id/dolphinTitle"
android:layout_marginLeft="30dip"
android:text="@string/minus_button"
android:textSize="70dip"
android:textStyle="bold"
android:gravity="center"
android:layout_marginTop="1dip"
android:background="@drawable/button_blue_square_selector"
android:textColor="#FFFFFF"
android:onClick="onClick"/>
<TextView
android:id="@+id/dolphinValue"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_marginLeft="15dip"
android:background="@android:drawable/editbox_background"
android:layout_toRightOf="@+id/dolphinMinusButton"
android:text="0"
android:textColor="#2E4C71"
android:textSize="50dip"
android:gravity="center"
android:textStyle="bold"
android:inputType="none"/>
<Button
android:id="@+id/dolphinPlusButton"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_toRightOf="@+id/dolphinValue"
android:layout_marginLeft="15dip"
android:text="@string/plus_button"
android:textSize="70dip"
android:textStyle="bold"
android:gravity="center"
android:layout_marginTop="1dip"
android:background="@drawable/button_blue_square_selector"
android:textColor="#FFFFFF"
android:onClick="onClick"/>
</RelativeLayout>


By this:



<view class="com.example.MyQuantityBox"
android:id="@+id/dolphinBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:myCustomAttribute="@string/my_title"/>


So, I do not want a custom layout, I want a custom View (it should not be possible for this view to have child).



The only thing that could change from one instance of a MyQuantityBox to another is the title. I would very much like to be able to specify this in the XML (as I do on the last XML line)



How can I do this? Should I put the RelativeLayout in a XML file in /res/layout and inflate it in my MyBoxQuantity class? If yes how do I do so?



Thanks!










share|improve this question














I am trying to create a custom View that would replace a certain layout that I use at multiple places, but I am struggling to do so.



Basically, I want to replace this:



<RelativeLayout
android:id="@+id/dolphinLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/background_box_light_blue"
android:padding="10dip"
android:layout_margin="10dip">
<TextView
android:id="@+id/dolphinTitle"
android:layout_width="200dip"
android:layout_height="100dip"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dip"
android:text="@string/my_title"
android:textSize="30dip"
android:textStyle="bold"
android:textColor="#2E4C71"
android:gravity="center"/>
<Button
android:id="@+id/dolphinMinusButton"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_toRightOf="@+id/dolphinTitle"
android:layout_marginLeft="30dip"
android:text="@string/minus_button"
android:textSize="70dip"
android:textStyle="bold"
android:gravity="center"
android:layout_marginTop="1dip"
android:background="@drawable/button_blue_square_selector"
android:textColor="#FFFFFF"
android:onClick="onClick"/>
<TextView
android:id="@+id/dolphinValue"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_marginLeft="15dip"
android:background="@android:drawable/editbox_background"
android:layout_toRightOf="@+id/dolphinMinusButton"
android:text="0"
android:textColor="#2E4C71"
android:textSize="50dip"
android:gravity="center"
android:textStyle="bold"
android:inputType="none"/>
<Button
android:id="@+id/dolphinPlusButton"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_toRightOf="@+id/dolphinValue"
android:layout_marginLeft="15dip"
android:text="@string/plus_button"
android:textSize="70dip"
android:textStyle="bold"
android:gravity="center"
android:layout_marginTop="1dip"
android:background="@drawable/button_blue_square_selector"
android:textColor="#FFFFFF"
android:onClick="onClick"/>
</RelativeLayout>


By this:



<view class="com.example.MyQuantityBox"
android:id="@+id/dolphinBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:myCustomAttribute="@string/my_title"/>


So, I do not want a custom layout, I want a custom View (it should not be possible for this view to have child).



The only thing that could change from one instance of a MyQuantityBox to another is the title. I would very much like to be able to specify this in the XML (as I do on the last XML line)



How can I do this? Should I put the RelativeLayout in a XML file in /res/layout and inflate it in my MyBoxQuantity class? If yes how do I do so?



Thanks!







android xml view






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 1 '10 at 20:34









nbarraillenbarraille

5,795125188




5,795125188













  • See "Compound Controls" in Android, and this link: stackoverflow.com/questions/1476371/…

    – greg7gkb
    Aug 9 '12 at 20:26



















  • See "Compound Controls" in Android, and this link: stackoverflow.com/questions/1476371/…

    – greg7gkb
    Aug 9 '12 at 20:26

















See "Compound Controls" in Android, and this link: stackoverflow.com/questions/1476371/…

– greg7gkb
Aug 9 '12 at 20:26





See "Compound Controls" in Android, and this link: stackoverflow.com/questions/1476371/…

– greg7gkb
Aug 9 '12 at 20:26












5 Answers
5






active

oldest

votes


















23














Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.



What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.



http://developer.android.com/guide/topics/ui/custom-components.html






share|improve this answer































    94














    A bit old, but I thought sharing how I'd do it, based on chubbsondubs' answer:
    I use FrameLayout (see Documentation), since it is used to contain a single view, and inflate into it the view from the xml.



    Code following:



    public class MyView extends FrameLayout {
    public MyView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    initView();
    }

    public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initView();
    }

    public MyView(Context context) {
    super(context);
    initView();
    }

    private void initView() {
    View view = inflate(getContext(), R.layout.my_view_layout, null);
    addView(view);
    }
    }





    share|improve this answer





















    • 6





      Since View class has static inflate() method there is no need for LayoutInflater.from()

      – outlying
      Jul 22 '13 at 14:22











    • thanks outlying, I've edited the code with your comment

      – Fox
      Dec 17 '13 at 19:00






    • 1





      Isn't this just the solution of Johannes from here: stackoverflow.com/questions/17836695/… Still, this inflates another layout within. So it's not really the best soltion I'd guess.

      – Tobias Reich
      Oct 18 '14 at 14:59






    • 2





      it is, but Johannes solution is from 7.24.13, and mind was from 7.1.13... Also, my solution uses FrameLayout which is supposed to contain only one View (as written in the doc referenced in the solution). So actually it is meant to be used as a placeholder for a View. I don't know any solution which doesn't invovle using a placeholder for the inflated View.

      – Fox
      Oct 18 '14 at 15:43













    • Maaaan, You Are COOL! You saved my brain!

      – Стас Пишевский
      Dec 1 '18 at 23:30



















    11














    Use the layout inflater , as i shown below



     public View myView(){
    View v; // Creating an instance for View Object
    LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = inflater.inflate(R.layout.myview, null);

    TextView text1 = (TextView) v.findViewById(R.id.dolphinTitle);
    Button btn1 = (Button) v.findViewById(R.id.dolphinMinusButton);
    TextView text2 = (TextView) v.findViewById(R.id. dolphinValue);
    Button btn2 = (Button) v.findViewById(R.id. dolphinPlusButton);


    return v;
    }





    share|improve this answer


























    • I have tried same. its working fine. but, when i click btn1, it will calling web services and after received response from server, i want to update some text in particular position text2..any help pls ?

      – harikrishnan
      Feb 10 '18 at 10:12



















    6














    In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:



    In my_table_row.xml:



    <?xml version="1.0" encoding="utf-8"?>
    <TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" android:id="@+id/myTableRow">
    <ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
    </TableRow>


    Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.



    for (int i=0; i<numRows; i++) {
    /*
    * 1. Make the row and attach it to myTable. For some reason this doesn't seem
    * to return the TableRow as you might expect from the xml, so you need to
    * receive the View it returns and then find the TableRow and other items, as
    * per step 2.
    */
    LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.my_table_row, myTable, true);

    // 2. Get all the things that we need to refer to to alter in any way.
    TableRow tr = (TableRow) v.findViewById(R.id.profileTableRow);
    ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
    TextView rowText = (TextView) v.findViewById(R.id.rowText);

    // 3. Configure them out as you need to
    rowText.setText("Text for this row");
    rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
    rowButton.setOnClickListener(this); // See note below ...

    /*
    * To ensure that when finding views by id on the next time round this
    * loop (or later) gie lots of spurious, unique, ids.
    */
    rowText.setId(1000+i);
    tr.setId(3000+i);
    }


    For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.






    share|improve this answer


























    • Hi Neil, I have tried same. its working fine. but, when i click rowButton, it will calling web services and after received response from server, i want to update some text in particular position rowText..any help pls ?

      – harikrishnan
      Feb 10 '18 at 10:00











    • see my question also. stackoverflow.com/questions/48719970/…

      – harikrishnan
      Feb 10 '18 at 10:58



















    2














    Here is a simple demo to create customview (compoundview) by inflating from xml



    attrs.xml



    <resources>

    <declare-styleable name="CustomView">
    <attr format="string" name="text"/>
    <attr format="reference" name="image"/>
    </declare-styleable>
    </resources>


    CustomView.kt



    class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    ConstraintLayout(context, attrs, defStyleAttr) {

    init {
    init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
    View.inflate(context, R.layout.custom_layout, this)

    val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
    try {
    val text = ta.getString(R.styleable.CustomView_text)
    val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
    if (drawableId != 0) {
    val drawable = AppCompatResources.getDrawable(context, drawableId)
    image_thumb.setImageDrawable(drawable)
    }
    text_title.text = text
    } finally {
    ta.recycle()
    }
    }
    }


    custom_layout.xml



    We should use merge here instead of ConstraintLayout because



    If we use ConstraintLayout here, layout hierarchy will be ConstraintLayout->ConstraintLayout -> ImageView + TextView => we have 1 redundant ConstraintLayout => not very good for performance



    <?xml version="1.0" encoding="utf-8"?>
    <merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:parentTag="android.support.constraint.ConstraintLayout">

    <ImageView
    android:id="@+id/image_thumb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:ignore="ContentDescription"
    tools:src="@mipmap/ic_launcher" />

    <TextView
    android:id="@+id/text_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="@id/image_thumb"
    app:layout_constraintStart_toStartOf="@id/image_thumb"
    app:layout_constraintTop_toBottomOf="@id/image_thumb"
    tools:text="Text" />

    </merge>


    Using
    activity_main.xml



    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <your_package.CustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#f00"
    app:image="@drawable/ic_android"
    app:text="Android" />

    <your_package.CustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#0f0"
    app:image="@drawable/ic_adb"
    app:text="ADB" />

    </LinearLayout>


    Result



    enter image description here



    Github demo






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4328838%2fcreate-a-custom-view-by-inflating-a-layout%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      23














      Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.



      What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.



      http://developer.android.com/guide/topics/ui/custom-components.html






      share|improve this answer




























        23














        Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.



        What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.



        http://developer.android.com/guide/topics/ui/custom-components.html






        share|improve this answer


























          23












          23








          23







          Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.



          What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.



          http://developer.android.com/guide/topics/ui/custom-components.html






          share|improve this answer













          Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.



          What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.



          http://developer.android.com/guide/topics/ui/custom-components.html







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 1 '10 at 20:48









          chubbsondubschubbsondubs

          25.8k2289124




          25.8k2289124

























              94














              A bit old, but I thought sharing how I'd do it, based on chubbsondubs' answer:
              I use FrameLayout (see Documentation), since it is used to contain a single view, and inflate into it the view from the xml.



              Code following:



              public class MyView extends FrameLayout {
              public MyView(Context context, AttributeSet attrs, int defStyle) {
              super(context, attrs, defStyle);
              initView();
              }

              public MyView(Context context, AttributeSet attrs) {
              super(context, attrs);
              initView();
              }

              public MyView(Context context) {
              super(context);
              initView();
              }

              private void initView() {
              View view = inflate(getContext(), R.layout.my_view_layout, null);
              addView(view);
              }
              }





              share|improve this answer





















              • 6





                Since View class has static inflate() method there is no need for LayoutInflater.from()

                – outlying
                Jul 22 '13 at 14:22











              • thanks outlying, I've edited the code with your comment

                – Fox
                Dec 17 '13 at 19:00






              • 1





                Isn't this just the solution of Johannes from here: stackoverflow.com/questions/17836695/… Still, this inflates another layout within. So it's not really the best soltion I'd guess.

                – Tobias Reich
                Oct 18 '14 at 14:59






              • 2





                it is, but Johannes solution is from 7.24.13, and mind was from 7.1.13... Also, my solution uses FrameLayout which is supposed to contain only one View (as written in the doc referenced in the solution). So actually it is meant to be used as a placeholder for a View. I don't know any solution which doesn't invovle using a placeholder for the inflated View.

                – Fox
                Oct 18 '14 at 15:43













              • Maaaan, You Are COOL! You saved my brain!

                – Стас Пишевский
                Dec 1 '18 at 23:30
















              94














              A bit old, but I thought sharing how I'd do it, based on chubbsondubs' answer:
              I use FrameLayout (see Documentation), since it is used to contain a single view, and inflate into it the view from the xml.



              Code following:



              public class MyView extends FrameLayout {
              public MyView(Context context, AttributeSet attrs, int defStyle) {
              super(context, attrs, defStyle);
              initView();
              }

              public MyView(Context context, AttributeSet attrs) {
              super(context, attrs);
              initView();
              }

              public MyView(Context context) {
              super(context);
              initView();
              }

              private void initView() {
              View view = inflate(getContext(), R.layout.my_view_layout, null);
              addView(view);
              }
              }





              share|improve this answer





















              • 6





                Since View class has static inflate() method there is no need for LayoutInflater.from()

                – outlying
                Jul 22 '13 at 14:22











              • thanks outlying, I've edited the code with your comment

                – Fox
                Dec 17 '13 at 19:00






              • 1





                Isn't this just the solution of Johannes from here: stackoverflow.com/questions/17836695/… Still, this inflates another layout within. So it's not really the best soltion I'd guess.

                – Tobias Reich
                Oct 18 '14 at 14:59






              • 2





                it is, but Johannes solution is from 7.24.13, and mind was from 7.1.13... Also, my solution uses FrameLayout which is supposed to contain only one View (as written in the doc referenced in the solution). So actually it is meant to be used as a placeholder for a View. I don't know any solution which doesn't invovle using a placeholder for the inflated View.

                – Fox
                Oct 18 '14 at 15:43













              • Maaaan, You Are COOL! You saved my brain!

                – Стас Пишевский
                Dec 1 '18 at 23:30














              94












              94








              94







              A bit old, but I thought sharing how I'd do it, based on chubbsondubs' answer:
              I use FrameLayout (see Documentation), since it is used to contain a single view, and inflate into it the view from the xml.



              Code following:



              public class MyView extends FrameLayout {
              public MyView(Context context, AttributeSet attrs, int defStyle) {
              super(context, attrs, defStyle);
              initView();
              }

              public MyView(Context context, AttributeSet attrs) {
              super(context, attrs);
              initView();
              }

              public MyView(Context context) {
              super(context);
              initView();
              }

              private void initView() {
              View view = inflate(getContext(), R.layout.my_view_layout, null);
              addView(view);
              }
              }





              share|improve this answer















              A bit old, but I thought sharing how I'd do it, based on chubbsondubs' answer:
              I use FrameLayout (see Documentation), since it is used to contain a single view, and inflate into it the view from the xml.



              Code following:



              public class MyView extends FrameLayout {
              public MyView(Context context, AttributeSet attrs, int defStyle) {
              super(context, attrs, defStyle);
              initView();
              }

              public MyView(Context context, AttributeSet attrs) {
              super(context, attrs);
              initView();
              }

              public MyView(Context context) {
              super(context);
              initView();
              }

              private void initView() {
              View view = inflate(getContext(), R.layout.my_view_layout, null);
              addView(view);
              }
              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 17 '13 at 18:59

























              answered Jul 1 '13 at 20:24









              FoxFox

              1,59511522




              1,59511522








              • 6





                Since View class has static inflate() method there is no need for LayoutInflater.from()

                – outlying
                Jul 22 '13 at 14:22











              • thanks outlying, I've edited the code with your comment

                – Fox
                Dec 17 '13 at 19:00






              • 1





                Isn't this just the solution of Johannes from here: stackoverflow.com/questions/17836695/… Still, this inflates another layout within. So it's not really the best soltion I'd guess.

                – Tobias Reich
                Oct 18 '14 at 14:59






              • 2





                it is, but Johannes solution is from 7.24.13, and mind was from 7.1.13... Also, my solution uses FrameLayout which is supposed to contain only one View (as written in the doc referenced in the solution). So actually it is meant to be used as a placeholder for a View. I don't know any solution which doesn't invovle using a placeholder for the inflated View.

                – Fox
                Oct 18 '14 at 15:43













              • Maaaan, You Are COOL! You saved my brain!

                – Стас Пишевский
                Dec 1 '18 at 23:30














              • 6





                Since View class has static inflate() method there is no need for LayoutInflater.from()

                – outlying
                Jul 22 '13 at 14:22











              • thanks outlying, I've edited the code with your comment

                – Fox
                Dec 17 '13 at 19:00






              • 1





                Isn't this just the solution of Johannes from here: stackoverflow.com/questions/17836695/… Still, this inflates another layout within. So it's not really the best soltion I'd guess.

                – Tobias Reich
                Oct 18 '14 at 14:59






              • 2





                it is, but Johannes solution is from 7.24.13, and mind was from 7.1.13... Also, my solution uses FrameLayout which is supposed to contain only one View (as written in the doc referenced in the solution). So actually it is meant to be used as a placeholder for a View. I don't know any solution which doesn't invovle using a placeholder for the inflated View.

                – Fox
                Oct 18 '14 at 15:43













              • Maaaan, You Are COOL! You saved my brain!

                – Стас Пишевский
                Dec 1 '18 at 23:30








              6




              6





              Since View class has static inflate() method there is no need for LayoutInflater.from()

              – outlying
              Jul 22 '13 at 14:22





              Since View class has static inflate() method there is no need for LayoutInflater.from()

              – outlying
              Jul 22 '13 at 14:22













              thanks outlying, I've edited the code with your comment

              – Fox
              Dec 17 '13 at 19:00





              thanks outlying, I've edited the code with your comment

              – Fox
              Dec 17 '13 at 19:00




              1




              1





              Isn't this just the solution of Johannes from here: stackoverflow.com/questions/17836695/… Still, this inflates another layout within. So it's not really the best soltion I'd guess.

              – Tobias Reich
              Oct 18 '14 at 14:59





              Isn't this just the solution of Johannes from here: stackoverflow.com/questions/17836695/… Still, this inflates another layout within. So it's not really the best soltion I'd guess.

              – Tobias Reich
              Oct 18 '14 at 14:59




              2




              2





              it is, but Johannes solution is from 7.24.13, and mind was from 7.1.13... Also, my solution uses FrameLayout which is supposed to contain only one View (as written in the doc referenced in the solution). So actually it is meant to be used as a placeholder for a View. I don't know any solution which doesn't invovle using a placeholder for the inflated View.

              – Fox
              Oct 18 '14 at 15:43







              it is, but Johannes solution is from 7.24.13, and mind was from 7.1.13... Also, my solution uses FrameLayout which is supposed to contain only one View (as written in the doc referenced in the solution). So actually it is meant to be used as a placeholder for a View. I don't know any solution which doesn't invovle using a placeholder for the inflated View.

              – Fox
              Oct 18 '14 at 15:43















              Maaaan, You Are COOL! You saved my brain!

              – Стас Пишевский
              Dec 1 '18 at 23:30





              Maaaan, You Are COOL! You saved my brain!

              – Стас Пишевский
              Dec 1 '18 at 23:30











              11














              Use the layout inflater , as i shown below



               public View myView(){
              View v; // Creating an instance for View Object
              LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
              v = inflater.inflate(R.layout.myview, null);

              TextView text1 = (TextView) v.findViewById(R.id.dolphinTitle);
              Button btn1 = (Button) v.findViewById(R.id.dolphinMinusButton);
              TextView text2 = (TextView) v.findViewById(R.id. dolphinValue);
              Button btn2 = (Button) v.findViewById(R.id. dolphinPlusButton);


              return v;
              }





              share|improve this answer


























              • I have tried same. its working fine. but, when i click btn1, it will calling web services and after received response from server, i want to update some text in particular position text2..any help pls ?

                – harikrishnan
                Feb 10 '18 at 10:12
















              11














              Use the layout inflater , as i shown below



               public View myView(){
              View v; // Creating an instance for View Object
              LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
              v = inflater.inflate(R.layout.myview, null);

              TextView text1 = (TextView) v.findViewById(R.id.dolphinTitle);
              Button btn1 = (Button) v.findViewById(R.id.dolphinMinusButton);
              TextView text2 = (TextView) v.findViewById(R.id. dolphinValue);
              Button btn2 = (Button) v.findViewById(R.id. dolphinPlusButton);


              return v;
              }





              share|improve this answer


























              • I have tried same. its working fine. but, when i click btn1, it will calling web services and after received response from server, i want to update some text in particular position text2..any help pls ?

                – harikrishnan
                Feb 10 '18 at 10:12














              11












              11








              11







              Use the layout inflater , as i shown below



               public View myView(){
              View v; // Creating an instance for View Object
              LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
              v = inflater.inflate(R.layout.myview, null);

              TextView text1 = (TextView) v.findViewById(R.id.dolphinTitle);
              Button btn1 = (Button) v.findViewById(R.id.dolphinMinusButton);
              TextView text2 = (TextView) v.findViewById(R.id. dolphinValue);
              Button btn2 = (Button) v.findViewById(R.id. dolphinPlusButton);


              return v;
              }





              share|improve this answer















              Use the layout inflater , as i shown below



               public View myView(){
              View v; // Creating an instance for View Object
              LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
              v = inflater.inflate(R.layout.myview, null);

              TextView text1 = (TextView) v.findViewById(R.id.dolphinTitle);
              Button btn1 = (Button) v.findViewById(R.id.dolphinMinusButton);
              TextView text2 = (TextView) v.findViewById(R.id. dolphinValue);
              Button btn2 = (Button) v.findViewById(R.id. dolphinPlusButton);


              return v;
              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 11 '12 at 5:17









              Sankar Ganesh

              10.3k115085




              10.3k115085










              answered Sep 10 '11 at 13:06









              TsunazeTsunaze

              1,05773477




              1,05773477













              • I have tried same. its working fine. but, when i click btn1, it will calling web services and after received response from server, i want to update some text in particular position text2..any help pls ?

                – harikrishnan
                Feb 10 '18 at 10:12



















              • I have tried same. its working fine. but, when i click btn1, it will calling web services and after received response from server, i want to update some text in particular position text2..any help pls ?

                – harikrishnan
                Feb 10 '18 at 10:12

















              I have tried same. its working fine. but, when i click btn1, it will calling web services and after received response from server, i want to update some text in particular position text2..any help pls ?

              – harikrishnan
              Feb 10 '18 at 10:12





              I have tried same. its working fine. but, when i click btn1, it will calling web services and after received response from server, i want to update some text in particular position text2..any help pls ?

              – harikrishnan
              Feb 10 '18 at 10:12











              6














              In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:



              In my_table_row.xml:



              <?xml version="1.0" encoding="utf-8"?>
              <TableRow xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent" android:id="@+id/myTableRow">
              <ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
              <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
              </TableRow>


              Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.



              for (int i=0; i<numRows; i++) {
              /*
              * 1. Make the row and attach it to myTable. For some reason this doesn't seem
              * to return the TableRow as you might expect from the xml, so you need to
              * receive the View it returns and then find the TableRow and other items, as
              * per step 2.
              */
              LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
              View v = inflater.inflate(R.layout.my_table_row, myTable, true);

              // 2. Get all the things that we need to refer to to alter in any way.
              TableRow tr = (TableRow) v.findViewById(R.id.profileTableRow);
              ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
              TextView rowText = (TextView) v.findViewById(R.id.rowText);

              // 3. Configure them out as you need to
              rowText.setText("Text for this row");
              rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
              rowButton.setOnClickListener(this); // See note below ...

              /*
              * To ensure that when finding views by id on the next time round this
              * loop (or later) gie lots of spurious, unique, ids.
              */
              rowText.setId(1000+i);
              tr.setId(3000+i);
              }


              For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.






              share|improve this answer


























              • Hi Neil, I have tried same. its working fine. but, when i click rowButton, it will calling web services and after received response from server, i want to update some text in particular position rowText..any help pls ?

                – harikrishnan
                Feb 10 '18 at 10:00











              • see my question also. stackoverflow.com/questions/48719970/…

                – harikrishnan
                Feb 10 '18 at 10:58
















              6














              In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:



              In my_table_row.xml:



              <?xml version="1.0" encoding="utf-8"?>
              <TableRow xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent" android:id="@+id/myTableRow">
              <ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
              <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
              </TableRow>


              Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.



              for (int i=0; i<numRows; i++) {
              /*
              * 1. Make the row and attach it to myTable. For some reason this doesn't seem
              * to return the TableRow as you might expect from the xml, so you need to
              * receive the View it returns and then find the TableRow and other items, as
              * per step 2.
              */
              LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
              View v = inflater.inflate(R.layout.my_table_row, myTable, true);

              // 2. Get all the things that we need to refer to to alter in any way.
              TableRow tr = (TableRow) v.findViewById(R.id.profileTableRow);
              ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
              TextView rowText = (TextView) v.findViewById(R.id.rowText);

              // 3. Configure them out as you need to
              rowText.setText("Text for this row");
              rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
              rowButton.setOnClickListener(this); // See note below ...

              /*
              * To ensure that when finding views by id on the next time round this
              * loop (or later) gie lots of spurious, unique, ids.
              */
              rowText.setId(1000+i);
              tr.setId(3000+i);
              }


              For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.






              share|improve this answer


























              • Hi Neil, I have tried same. its working fine. but, when i click rowButton, it will calling web services and after received response from server, i want to update some text in particular position rowText..any help pls ?

                – harikrishnan
                Feb 10 '18 at 10:00











              • see my question also. stackoverflow.com/questions/48719970/…

                – harikrishnan
                Feb 10 '18 at 10:58














              6












              6








              6







              In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:



              In my_table_row.xml:



              <?xml version="1.0" encoding="utf-8"?>
              <TableRow xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent" android:id="@+id/myTableRow">
              <ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
              <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
              </TableRow>


              Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.



              for (int i=0; i<numRows; i++) {
              /*
              * 1. Make the row and attach it to myTable. For some reason this doesn't seem
              * to return the TableRow as you might expect from the xml, so you need to
              * receive the View it returns and then find the TableRow and other items, as
              * per step 2.
              */
              LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
              View v = inflater.inflate(R.layout.my_table_row, myTable, true);

              // 2. Get all the things that we need to refer to to alter in any way.
              TableRow tr = (TableRow) v.findViewById(R.id.profileTableRow);
              ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
              TextView rowText = (TextView) v.findViewById(R.id.rowText);

              // 3. Configure them out as you need to
              rowText.setText("Text for this row");
              rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
              rowButton.setOnClickListener(this); // See note below ...

              /*
              * To ensure that when finding views by id on the next time round this
              * loop (or later) gie lots of spurious, unique, ids.
              */
              rowText.setId(1000+i);
              tr.setId(3000+i);
              }


              For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.






              share|improve this answer















              In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:



              In my_table_row.xml:



              <?xml version="1.0" encoding="utf-8"?>
              <TableRow xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent" android:id="@+id/myTableRow">
              <ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
              <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
              </TableRow>


              Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.



              for (int i=0; i<numRows; i++) {
              /*
              * 1. Make the row and attach it to myTable. For some reason this doesn't seem
              * to return the TableRow as you might expect from the xml, so you need to
              * receive the View it returns and then find the TableRow and other items, as
              * per step 2.
              */
              LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
              View v = inflater.inflate(R.layout.my_table_row, myTable, true);

              // 2. Get all the things that we need to refer to to alter in any way.
              TableRow tr = (TableRow) v.findViewById(R.id.profileTableRow);
              ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
              TextView rowText = (TextView) v.findViewById(R.id.rowText);

              // 3. Configure them out as you need to
              rowText.setText("Text for this row");
              rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
              rowButton.setOnClickListener(this); // See note below ...

              /*
              * To ensure that when finding views by id on the next time round this
              * loop (or later) gie lots of spurious, unique, ids.
              */
              rowText.setId(1000+i);
              tr.setId(3000+i);
              }


              For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 23 '17 at 12:02









              Community

              11




              11










              answered Mar 1 '12 at 11:25









              Neil TownsendNeil Townsend

              5,21842949




              5,21842949













              • Hi Neil, I have tried same. its working fine. but, when i click rowButton, it will calling web services and after received response from server, i want to update some text in particular position rowText..any help pls ?

                – harikrishnan
                Feb 10 '18 at 10:00











              • see my question also. stackoverflow.com/questions/48719970/…

                – harikrishnan
                Feb 10 '18 at 10:58



















              • Hi Neil, I have tried same. its working fine. but, when i click rowButton, it will calling web services and after received response from server, i want to update some text in particular position rowText..any help pls ?

                – harikrishnan
                Feb 10 '18 at 10:00











              • see my question also. stackoverflow.com/questions/48719970/…

                – harikrishnan
                Feb 10 '18 at 10:58

















              Hi Neil, I have tried same. its working fine. but, when i click rowButton, it will calling web services and after received response from server, i want to update some text in particular position rowText..any help pls ?

              – harikrishnan
              Feb 10 '18 at 10:00





              Hi Neil, I have tried same. its working fine. but, when i click rowButton, it will calling web services and after received response from server, i want to update some text in particular position rowText..any help pls ?

              – harikrishnan
              Feb 10 '18 at 10:00













              see my question also. stackoverflow.com/questions/48719970/…

              – harikrishnan
              Feb 10 '18 at 10:58





              see my question also. stackoverflow.com/questions/48719970/…

              – harikrishnan
              Feb 10 '18 at 10:58











              2














              Here is a simple demo to create customview (compoundview) by inflating from xml



              attrs.xml



              <resources>

              <declare-styleable name="CustomView">
              <attr format="string" name="text"/>
              <attr format="reference" name="image"/>
              </declare-styleable>
              </resources>


              CustomView.kt



              class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
              ConstraintLayout(context, attrs, defStyleAttr) {

              init {
              init(attrs)
              }

              private fun init(attrs: AttributeSet?) {
              View.inflate(context, R.layout.custom_layout, this)

              val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
              try {
              val text = ta.getString(R.styleable.CustomView_text)
              val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
              if (drawableId != 0) {
              val drawable = AppCompatResources.getDrawable(context, drawableId)
              image_thumb.setImageDrawable(drawable)
              }
              text_title.text = text
              } finally {
              ta.recycle()
              }
              }
              }


              custom_layout.xml



              We should use merge here instead of ConstraintLayout because



              If we use ConstraintLayout here, layout hierarchy will be ConstraintLayout->ConstraintLayout -> ImageView + TextView => we have 1 redundant ConstraintLayout => not very good for performance



              <?xml version="1.0" encoding="utf-8"?>
              <merge xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              xmlns:tools="http://schemas.android.com/tools"
              tools:parentTag="android.support.constraint.ConstraintLayout">

              <ImageView
              android:id="@+id/image_thumb"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              tools:ignore="ContentDescription"
              tools:src="@mipmap/ic_launcher" />

              <TextView
              android:id="@+id/text_title"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              app:layout_constraintEnd_toEndOf="@id/image_thumb"
              app:layout_constraintStart_toStartOf="@id/image_thumb"
              app:layout_constraintTop_toBottomOf="@id/image_thumb"
              tools:text="Text" />

              </merge>


              Using
              activity_main.xml



              <?xml version="1.0" encoding="utf-8"?>
              <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

              <your_package.CustomView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:background="#f00"
              app:image="@drawable/ic_android"
              app:text="Android" />

              <your_package.CustomView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:background="#0f0"
              app:image="@drawable/ic_adb"
              app:text="ADB" />

              </LinearLayout>


              Result



              enter image description here



              Github demo






              share|improve this answer




























                2














                Here is a simple demo to create customview (compoundview) by inflating from xml



                attrs.xml



                <resources>

                <declare-styleable name="CustomView">
                <attr format="string" name="text"/>
                <attr format="reference" name="image"/>
                </declare-styleable>
                </resources>


                CustomView.kt



                class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
                ConstraintLayout(context, attrs, defStyleAttr) {

                init {
                init(attrs)
                }

                private fun init(attrs: AttributeSet?) {
                View.inflate(context, R.layout.custom_layout, this)

                val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
                try {
                val text = ta.getString(R.styleable.CustomView_text)
                val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
                if (drawableId != 0) {
                val drawable = AppCompatResources.getDrawable(context, drawableId)
                image_thumb.setImageDrawable(drawable)
                }
                text_title.text = text
                } finally {
                ta.recycle()
                }
                }
                }


                custom_layout.xml



                We should use merge here instead of ConstraintLayout because



                If we use ConstraintLayout here, layout hierarchy will be ConstraintLayout->ConstraintLayout -> ImageView + TextView => we have 1 redundant ConstraintLayout => not very good for performance



                <?xml version="1.0" encoding="utf-8"?>
                <merge xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                tools:parentTag="android.support.constraint.ConstraintLayout">

                <ImageView
                android:id="@+id/image_thumb"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                tools:ignore="ContentDescription"
                tools:src="@mipmap/ic_launcher" />

                <TextView
                android:id="@+id/text_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_constraintEnd_toEndOf="@id/image_thumb"
                app:layout_constraintStart_toStartOf="@id/image_thumb"
                app:layout_constraintTop_toBottomOf="@id/image_thumb"
                tools:text="Text" />

                </merge>


                Using
                activity_main.xml



                <?xml version="1.0" encoding="utf-8"?>
                <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <your_package.CustomView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#f00"
                app:image="@drawable/ic_android"
                app:text="Android" />

                <your_package.CustomView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#0f0"
                app:image="@drawable/ic_adb"
                app:text="ADB" />

                </LinearLayout>


                Result



                enter image description here



                Github demo






                share|improve this answer


























                  2












                  2








                  2







                  Here is a simple demo to create customview (compoundview) by inflating from xml



                  attrs.xml



                  <resources>

                  <declare-styleable name="CustomView">
                  <attr format="string" name="text"/>
                  <attr format="reference" name="image"/>
                  </declare-styleable>
                  </resources>


                  CustomView.kt



                  class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
                  ConstraintLayout(context, attrs, defStyleAttr) {

                  init {
                  init(attrs)
                  }

                  private fun init(attrs: AttributeSet?) {
                  View.inflate(context, R.layout.custom_layout, this)

                  val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
                  try {
                  val text = ta.getString(R.styleable.CustomView_text)
                  val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
                  if (drawableId != 0) {
                  val drawable = AppCompatResources.getDrawable(context, drawableId)
                  image_thumb.setImageDrawable(drawable)
                  }
                  text_title.text = text
                  } finally {
                  ta.recycle()
                  }
                  }
                  }


                  custom_layout.xml



                  We should use merge here instead of ConstraintLayout because



                  If we use ConstraintLayout here, layout hierarchy will be ConstraintLayout->ConstraintLayout -> ImageView + TextView => we have 1 redundant ConstraintLayout => not very good for performance



                  <?xml version="1.0" encoding="utf-8"?>
                  <merge xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:app="http://schemas.android.com/apk/res-auto"
                  xmlns:tools="http://schemas.android.com/tools"
                  tools:parentTag="android.support.constraint.ConstraintLayout">

                  <ImageView
                  android:id="@+id/image_thumb"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  tools:ignore="ContentDescription"
                  tools:src="@mipmap/ic_launcher" />

                  <TextView
                  android:id="@+id/text_title"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  app:layout_constraintEnd_toEndOf="@id/image_thumb"
                  app:layout_constraintStart_toStartOf="@id/image_thumb"
                  app:layout_constraintTop_toBottomOf="@id/image_thumb"
                  tools:text="Text" />

                  </merge>


                  Using
                  activity_main.xml



                  <?xml version="1.0" encoding="utf-8"?>
                  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:app="http://schemas.android.com/apk/res-auto"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:orientation="vertical">

                  <your_package.CustomView
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:background="#f00"
                  app:image="@drawable/ic_android"
                  app:text="Android" />

                  <your_package.CustomView
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:background="#0f0"
                  app:image="@drawable/ic_adb"
                  app:text="ADB" />

                  </LinearLayout>


                  Result



                  enter image description here



                  Github demo






                  share|improve this answer













                  Here is a simple demo to create customview (compoundview) by inflating from xml



                  attrs.xml



                  <resources>

                  <declare-styleable name="CustomView">
                  <attr format="string" name="text"/>
                  <attr format="reference" name="image"/>
                  </declare-styleable>
                  </resources>


                  CustomView.kt



                  class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
                  ConstraintLayout(context, attrs, defStyleAttr) {

                  init {
                  init(attrs)
                  }

                  private fun init(attrs: AttributeSet?) {
                  View.inflate(context, R.layout.custom_layout, this)

                  val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
                  try {
                  val text = ta.getString(R.styleable.CustomView_text)
                  val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
                  if (drawableId != 0) {
                  val drawable = AppCompatResources.getDrawable(context, drawableId)
                  image_thumb.setImageDrawable(drawable)
                  }
                  text_title.text = text
                  } finally {
                  ta.recycle()
                  }
                  }
                  }


                  custom_layout.xml



                  We should use merge here instead of ConstraintLayout because



                  If we use ConstraintLayout here, layout hierarchy will be ConstraintLayout->ConstraintLayout -> ImageView + TextView => we have 1 redundant ConstraintLayout => not very good for performance



                  <?xml version="1.0" encoding="utf-8"?>
                  <merge xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:app="http://schemas.android.com/apk/res-auto"
                  xmlns:tools="http://schemas.android.com/tools"
                  tools:parentTag="android.support.constraint.ConstraintLayout">

                  <ImageView
                  android:id="@+id/image_thumb"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  tools:ignore="ContentDescription"
                  tools:src="@mipmap/ic_launcher" />

                  <TextView
                  android:id="@+id/text_title"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  app:layout_constraintEnd_toEndOf="@id/image_thumb"
                  app:layout_constraintStart_toStartOf="@id/image_thumb"
                  app:layout_constraintTop_toBottomOf="@id/image_thumb"
                  tools:text="Text" />

                  </merge>


                  Using
                  activity_main.xml



                  <?xml version="1.0" encoding="utf-8"?>
                  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:app="http://schemas.android.com/apk/res-auto"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:orientation="vertical">

                  <your_package.CustomView
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:background="#f00"
                  app:image="@drawable/ic_android"
                  app:text="Android" />

                  <your_package.CustomView
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:background="#0f0"
                  app:image="@drawable/ic_adb"
                  app:text="ADB" />

                  </LinearLayout>


                  Result



                  enter image description here



                  Github demo







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 2 at 3:46









                  Phan Van LinhPhan Van Linh

                  21.8k11117142




                  21.8k11117142






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4328838%2fcreate-a-custom-view-by-inflating-a-layout%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith