In My App Using One Activity And I Am Using Two Fragment. How Can We Swap The Fragment In Activity?
* First Create Project With Empty Activity.
*After That Create Two Fragment.
* Create This Code MainActivity.XML Page
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="waytofeed.wapptech.com.demo15.MainActivity" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="35dp" android:text="Click" android:id="@+id/button"/> fragment android:layout_width="match_parent" android:layout_height="match_parent" android:name="waytofeed.wapptech.com.demo15.page1" android:layout_weight="1" android:id="@+id/frag1"> </fragment> fragment android:layout_width="match_parent" android:layout_height="match_parent" android:name="waytofeed.wapptech.com.demo15.page2" android:layout_weight="1" android:id="@+id/frag2"> fragment> </LinearLayout>
After That In MainActivity.java File Add This Code:)
public class MainActivity extends AppCompatActivity implements View.OnClickListener { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=findViewById(R.id.button); button.setOnClickListener(this); } @Override public void onClick(View view) { Fragment fm= new page2(); FragmentTransaction ft=getFragmentManager().beginTransaction(); ft.replace(R.id.frag1,fm); ft.commit(); } }
Always Remember Import This Package All Java File:)
import android.app.Fragment;