Fragment Demo 1
Fragment Demo 1
xml
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragment"
android:background="@android:color/holo_purple"
android:layout_width="match_parent"
android:layout_height="400dp" />
<Button
android:id="@+id/btnChange"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Change" />
</LinearLayout>
**fragment_first.xml
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="First Fragment"
android:textSize="30dp"
android:textAlignment="center"/>
<ImageView
android:id="@+id/imageView2"
android:layout_width="300dp"
android:layout_height="300dp"
android:src="@drawable/jasmine" />
</LinearLayout>
**fragment_second.xml
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
**MainActivity.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
**FirstFragment.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
**SecondFragment.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
**Output