There is a task: you need to dynamically create a button. The description of the button is in the xml file:

<Button android:layout_width="80sp" android:layout_height="80sp" android:gravity="center_vertical" android:background="@drawable/ring_button" android:id="@+id/button5" android:enabled="false" android:layout_alignTop="@+id/button4" android:layout_alignLeft="@+id/button3" android:layout_alignStart="@+id/button3" /> 

As you can see, background refers to another xml file (ring_button.xml):

 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <solid android:color="#EEEEEE"/> <stroke android:width="12sp" android:color="#fff" /> </shape> 

How to dynamically create a button described in these files?

    2 answers 2

    Create the layout_your_button.xml file in the layout folder:

     <?xml version="1.0" encoding="utf-8"?> <Button xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="80sp" android:layout_height="80sp" android:gravity="center_vertical" android:background="@drawable/ring_button" android:id="@+id/button5" android:enabled="false" /> 

    Further in the code where you need to create a button dynamically:

     Button button = (Button) LayoutInflator.from(context).inflate(R.layout_your_button, null); 

    In general, in the same way as a list item to create ( ListView ). Worked with lists with a custom element?

    • Is it possible in more detail, what happens in the code? - DeathCookies
    • It is desirable and immediately specify the parent container, otherwise then you will have to set all the layout_* again when added to the container. - Eugene Krivenja 5:41
    • @DeathCookies; With the help of LayoutInflator is created from xml View , in your case it is a button. - Vladyslav Matviienko 5:42

    For this there is a LayoutInflater :

     LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE ); View view = inflater.inflate(R.layout.NAME_OF_LAYOUT_FILE, null); 

    or

     View view = LayoutInflator.from(context).inflate(R.layout.NAME_OF_LAYOUT_FILE, null); 
    • Context has no getLayoutInflater () method - Vladyslav Matviienko
    • @metalurgus, yes, hurried with the answer. corrected. - JuriySPb