Reputation: 65
How can I programmatically include a layout in a specific spot in another layout?
For example, if I have a layout like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/some_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, world!"
/>
// INCLUDE HERE
</LinearLayout>
</LinearLayout>
How can I include the following layout (programmatically) in that specific location in the parent layout?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/some_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
Upvotes: 1
Views: 548
Reputation: 190
Add id to the vertical oriented linear layout (ex: master view). and the code for your dynamic view is below.
LinearLayout masterView = (LinearLayout)findViewById(R.id.masterView);
LinearLayout childView = new LinearLayout(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
childView.setLayoutParams(lp);
LinearLayout childToChildView = new LinearLayout(this);
childToChildView.setLayoutParams(lp);
ImageView imageView = new ImageView(this);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(layoutParams);
imageView.setId(View.generateViewId());//some integer number
childToChildView.addView(imageView);
childView.addView(childToChildView);
masterView.addView(childView);
Upvotes: 1