If you have a complex layout that you want to create programmatically, it might be easiest to make the layout in xml and then just inflate it and add it at run time.
Create view in xml
Here is a sample of the finished xml layout, which is located in the layout folder. Yours can be any, single view or complex layout.
Layout / my_view.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/LinearLayout1" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextView1" android:text="This is a TV"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextView2" android:text="How are you today?"/> </LinearLayout>
Create a container to view
Put space in your layout for your work. You may have something like this.
<FrameLayout android:id="@+id/flContainer" android:layout_width="wrap_content" android:layout_height="wrap_content"> </FrameLayout>
Click view
Use the link to the container, inflate your view from xml and add it to the container.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FrameLayout container = (FrameLayout) findViewById(R.id.flContainer); View inflatedLayout= getLayoutInflater().inflate(R.layout.my_view, null, false); container.addView(inflatedLayout); }
Doing this in this way makes your code much cleaner.
See also:
source share