Using fragment to dynamically add layout in Android

1. Add linearlayout with empty content to layout_main.xml

<HorizontalScrollView
    android:id="@+id/listimage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    />

2. Create a new fragmentlistimage.xml file to store the added 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="match_parent"
    android:orientation="horizontal"
    >

        <ImageView
            android:id="@+id/first"
            android:layout_width="180dp"
            android:layout_height="100dp"
            android:src="@drawable/blue_ocean"/>
        <ImageView
            android:id="@+id/first1"
            android:layout_width="180dp"
            android:layout_height="100dp"
            android:src="@drawable/blue_ocean01"/>
        <ImageView
            android:id="@+id/first2"
            android:layout_width="180dp"
            android:layout_height="100dp"
            android:src="@drawable/blue_ocean05"/>
        <ImageView
            android:id="@+id/first3"
            android:layout_width="180dp"
            android:layout_height="100dp"
            android:src="@drawable/blue_ocean06"/>
        <ImageView
            android:id="@+id/first4"
            android:layout_width="180dp"
            android:layout_height="100dp"
            android:src="@drawable/blue_ocean07"/>
        <ImageView
            android:id="@+id/first5"
            android:layout_width="180dp"
            android:layout_height="100dp"
            android:src="@drawable/blue_ocean09"/>
        
       
</LinearLayout>

3. Create a new java class file and return the view of fragmentlistimage.xml

public class fragmentlistimage extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragmentlistimage,container,false);
    }
}

4. Add layout in MainActivity class file

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction().add(R.id.listimage,new fragmentlistimage()).commit();
    }
}

Guess you like

Origin blog.csdn.net/ED_LAI/article/details/132448479