Call fragment from fragment - android

i have an activity with button on it and when a click i call the fragment with another button on fragment. but when click on fragment's button i cant call a second fragment. this is my source, pretty simple:
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity" >
<Button
android:id="#+id/btn_click"
android:text="Call Fragment"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:onClick="onClick"
/>
</LinearLayout>
fragment1.xml
<?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:background="#f0f0f0"
android:orientation="vertical" >
<TextView
android:id="#+id/fragment1"
android:text="Fragment 1"
android:textSize="25sp"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<Button
android:id="#+id/btn_frag2"
android:text="Call Fragment 2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
fragment2.xml
<?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:background="#f0f0f0"
android:orientation="vertical" >
<TextView
android:id="#+id/fragment2"
android:text="Fragment 2"
android:textSize="25sp"
android:gravity="center_vertical|center_horizontal"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onClick(View v) {
Fragment1 fragment1 = new Fragment1();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment1);
fragmentTransaction.commit();
}
}
Fragment1.java
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
public void onClick2(View view) {
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment1, fragment2);
fragmentTransaction.commit();
}
}
Fragment2.java
public class Fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
}
what is wrong in my code?

I think now Fragment nesting is available just update the back computability jar
now lets dig in the problem it self .
public void onClick2(View view) {
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment1, fragment2);
fragmentTransaction.commit();
}
I think the R.id.fragment1 belongs to a TextView which is not a good place to include child views in because its not a ViewGroup, you can remove the textView from the xml and replace it with a LinearLayout lets say and it will work , if not tell me what the error .
fragment1.xml
<?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:background="#f0f0f0"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/fragment1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<Button
android:id="#+id/btn_frag2"
android:text="Call Fragment 2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Update for the error in the comment
public class Fragment1 extends Fragment implements OnClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment1, container, false);
((Button) v.findViewById(R.id.btn_frag2)).setOnClickListener(this);
return v;
}
public void onClick(View view) {
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}

If you want to replace the entire Fragment1 with Fragment2, you need to do it inside MainActivity, by using:
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment2);
fragmentTransaction.commit();
Just put this code inside a method in MainActivity, then call that method from Fragment1.

This is my answer which solved the same problem. Fragment2.java is the fragment class which holds the layout of fragment2.xml.
public void onClick(View v) {
Fragment fragment2 = new Fragement2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}

I would use a listener. Fragment1 calling the listener (main activity)

This code works for me to call the parent_fragment method from child_fragment.
ParentFragment parent = (ParentFragment) activity.getFragmentManager().findViewById(R.id.contaniner);
parent.callMethod();

In MainActivity
private static android.support.v4.app.FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
}
public void secondFragment() {
fragmentManager
.beginTransaction()
.setCustomAnimations(R.anim.right_enter, R.anim.left_out)
.replace(R.id.frameContainer, new secondFragment(), "secondFragmentTag").addToBackStack(null)
.commit();
}
In FirstFragment call SecondFrgment Like this:
new MainActivity().secondFragment();

Just do that: getTabAt(index of your tab)
ActionBar actionBar = getSupportActionBar();
actionBar.selectTab(actionBar.getTabAt(0));

Related

How to switch existing fragments when the dialog is closed?

The main screen of the app is for bottom navigation.
And there are 3 menus, all of which are fragments.
Pressing the button on one of the fragments opens the dialog fragment window.
And when the dialog is closed, the old fragment should be switched to another new fragment.
I use show() and hide() instead of replace().
MainAcitivity.java
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNav;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
Fragment curFrag = fm.getPrimaryNavigationFragment();
String tag = String.valueOf(item.getItemId());
int id = item.getItemId();
if(curFrag != null) {
transaction.hide(curFrag);
}
Fragment fragment = fm.findFragmentByTag(tag);
if(fragment == null) {
if(id == R.id.list)
fragment = new WorkoutListFragment();
transaction.add(R.id.content_layout, fragment);
}
else {
transaction.show(fragment);
}
transaction.setPrimaryNavigationFragment(fragment);
transaction.setReorderingAllowed(true);
transaction.commitNow();
return true;
}
});
}
// Switch to another fragment when the dialog is closed
public void onFragmentChanged() {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
String tag = "ABC";
Fragment currentFragment = fragmentManager.getPrimaryNavigationFragment();
if (currentFragment != null) {
fragmentTransaction.hide(currentFragment);
}
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if (fragment == null) {
fragment = new WriteRoutineFragment();
fragmentTransaction.add(R.id.container, fragment, tag);
} else {
fragmentTransaction.show(fragment);
}
fragmentTransaction.setPrimaryNavigationFragment(fragment);
fragmentTransaction.setReorderingAllowed(true);
fragmentTransaction.commitNow();
}
}
DialogFragment.java
Button startBtn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_body_part_dialog, null);
startBtn = view.findViewById(R.id.check);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity activity = (MainActivity) getActivity();
activity.onFragmentChanged(); // change fragment
dismiss();
}
});
return view;
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
}
WriteRoutineFragment.java
public class WriteRoutineFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_write_routine, container, false);
return rootView;
}
}
ERROR
java.lang.IllegalArgumentException: No view found for id 0x7f0a0082 (com.example.writeweight:id/container) for fragment WriteRoutineFragment{f3a9b6 (137e8e27-12af-4e5a-9397-2cbdc80ed980) id=0x7f0a0082 ABC}
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:875)
at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2100)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1874)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1830)
at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManagerImpl.java:1696)
at androidx.fragment.app.BackStackRecord.commitNow(BackStackRecord.java:293)
at com.example.writeweight.activity.MainActivity.onFragmentChanged(MainActivity.java:78)
at com.example.writeweight.fragment.BodyPartDialogFragment$2.onClick(BodyPartDialogFragment.java:89)
at android.view.View.performClick(View.java:8160)
at android.widget.TextView.performClick(TextView.java:16221)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View.performClickInternal(View.java:8137)
at android.view.View.access$3700(View.java:888)
at android.view.View$PerformClick.run(View.java:30236)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8506)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
I/Process: Sending signal. PID: 23516 SIG: 9
ADDED
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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=".activity.MainActivity">
<FrameLayout
android:id="#+id/content_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="#id/bottom_nav"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu"/>
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_write_routine.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragment.WriteRoutineFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
When you say
fragmentTransaction.add(R.id.container, fragment, tag);
What you're saying is that you want the FragmentManager to find the R.id.container in your layout and add your fragment to that container. As you're using getSupportFragmentManager(), you're using the Activity's FragmentManager and hence, R.id.container needs to be in your activity's layout. However, R.id.container isn't in your activity's layout, which is why you're getting an exception.
Instead, you should be using the container that is in your Activity's layout - R.id.content_layout:
fragmentTransaction.add(R.id.content_layout, fragment, tag);

Implement Bottom Navigation View into a fragment

In my Android Studio project I want to implement into the MainActivity a NavigationDrawer with fragments and on every fragments a bottom navigation view.
This is the code of one fragment:
public class U16 extends Fragment{
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("TITOLO U16");
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (item.getItemId()) {
case R.id.navigation_home:
fragmentTransaction.replace(R.id.content, new Calendario()).commit();
return true;
case R.id.navigation_dashboard:
fragmentTransaction.replace(R.id.content, new Palestre()).commit();
return true;
case R.id.navigation_notifications:
fragmentTransaction.replace(R.id.content, new Squadra()).commit();
return true;
}
return false;
}
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
BottomNavigationView navigation = (BottomNavigationView) getActivity().findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content, new Calendario()).commit();
return inflater.inflate(R.layout.u16_layout, container, false);
}
}
I get this error:
FATAL EXCEPTION: main
Process: app.navigationdrawerfragment, PID: 21499
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.BottomNavigationView.setOnNavigationItemSelectedListener(android.support.design.widget.BottomNavigationView$OnNavigationItemSelectedListener)' on a null object reference at app.navigationdrawerfragment.U16.onCreateView(U16.java:52)
I know that this error in into the procedure "OnCreateView" doing " navigation.setOnNavigationItemSelectedListener..."
This is the u16_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="simone.biliato.navigationdrawerfragment.MainActivity">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/navigation" />
</LinearLayout>
So, anyone tried to do the same?
You are trying do set someone that is isn't already created.
So move the code into the event onViewCreated, like this:
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Titolo");
BottomNavigationView navigation = (BottomNavigationView) getActivity().findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content, new Calendario()).commit();
return inflater.inflate(R.layout.u16_layout, container, false);
}
This will work :)

How to add Fragment into Activity in Android

I want add 2 fragment into activity, and when click on button switch between this fragments!
I want show Fragment_1 for by default in activity (my mean is : when running activity, show fragment_1) and when click on button switch between fragment_2 and fragment_1 !
I write below codes, and when running activity show fragment_1 but when click on button for switch between fragments, show me Force Close error.
FC error :
08-27 14:15:41.363 14224-14224/com.mohammad.nouri.diaryday E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mohammad.nouri.diaryday, PID: 14224
java.lang.IllegalStateException: commit already called
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:641)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:621)
at com.mohammad.nouri.diaryday.Activities.LoginActivity$1.onClick(LoginActivity.java:58)
at android.view.View.performClick(View.java:4764)
at android.view.View$PerformClick.run(View.java:19844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5349)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Activity codes:
public class LoginActivity extends AppCompatActivity {
private Context context;
private boolean status = false;
FragmentTransaction fT;
FragmentManager fM;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
context = this;
Glide.with(this).load(R.drawable.login_header_image)
.bitmapTransform(new BlurTransformation(context, 20))
.into((ImageView) findViewById(R.id.login_background));
fM = getSupportFragmentManager();
fT = fM.beginTransaction();
if (!status) {
LoginFragment f1 = new LoginFragment();
fT.add(R.id.login_cardView, f1);
fT.commit();
status = true;
}
FloatingActionButton f = (FloatingActionButton) findViewById(R.id.login_registerButton);
f.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!status) {
RegisterFragment f1 = new RegisterFragment();
fT.add(R.id.login_cardView, f1);
fT.commit();
status = true;
}else {
LoginFragment f2 = new LoginFragment();
fT.add(R.id.login_cardView, f2);
fT.commit();
status = false;
}
}
});
}
}
How can I fix it ? Thanks all <3
You only call commit() once in a FragmentTransaction which you already do in the onCreate(). So, just create a new FragmentTransaction within your fab:
FloatingActionButton f = (FloatingActionButton) findViewById(R.id.login_registerButton);
f.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!status) {
RegisterFragment f1 = new RegisterFragment();
fM.beginTransaction().add(R.id.login_cardView, f1)
.commit();
status = true;
}else {
LoginFragment f2 = new LoginFragment();
fM.beginTransaction().add(R.id.login_cardView, f2)
.commit();
status = false;
}
}
});
Instead of adding the fragments try replacing because you have already added once above.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btnFragment;
LinearLayout fragmentContainer;
boolean toggleFlag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentContainer = (LinearLayout) findViewById(R.id.fragment_container);
FragmentA fragmentA = new FragmentA();
final FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragmentA);
fragmentTransaction.commit();
btnFragment = (Button) findViewById(R.id.btn_fragment);
btnFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(toggleFlag) {
FragmentA fragmentA = new FragmentA();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragmentA);
fragmentTransaction.commit();
} else {
FragmentB fragmentB = new FragmentB();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragmentB);
fragmentTransaction.commit();
}
toggleFlag = !toggleFlag;
}
});
}
}
activity_main.xml
<?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="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btn_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Toggle Fragment" />
</LinearLayout>
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
FragmentA.java
public class FragmentA extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.layout_fragment_a, null);
return rootview;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
layout_fragment_a.xml
<?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="vertical">
<ImageView
android:id="#+id/picture"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#mipmap/ic_launcher"/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Demo Fragment A"
android:textColor="#android:color/black"/>
</LinearLayout>
FragmentB.java
public class FragmentB extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.layout_fragment_b, null);
return rootview;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
layout_fragment_b.xml
<?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="vertical">
<ImageView
android:id="#+id/picture"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#mipmap/ic_launcher"/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Demo Fragment B"
android:textColor="#android:color/black"/>
</LinearLayout>
use this method to call fragment
rplaceFragment(Fragment fragment , int id){
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(id, fragment);
fragmentTransaction.commit();
}

Changing fragments

I am trying to show different fragments depending on whether GPS is enabled or not. But I am getting this error :-
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0e00a1
Please advise me how to do this:
Here is my MainActivity class:
public class MainActivity extends Activity {
Fragment fr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
fr = new FragmentTwo();
getFragment();
} else {
fr = new FragmentOne();
getFragment();
}
}
public void getFragment() {
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
}
FragmentOne:-
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
FragmentTwo:-
public class FragmentTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
My activity_main:-
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="#+id/fragment_place"
android:name="com.test.FragmentTwo"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
And the fragment_one.xml and fragment_two.xml are same just the different text:-
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="GPS IS ENABLE"/>
</RelativeLayout>
Thanks in advance.
Replace
<fragment
android:id="#+id/fragment_place"
android:name="com.test.FragmentTwo"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
With
<FrameLayout
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent" />
As static Fragment can not be replace at run time. But you can add or replace fragment in FrameLayout.
You can remove this line
android:name="com.test.FragmentTwo"
<fragment
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

How to replace fragment to another fragment in TabLayout and ViewPager

I want to replace fragment to another fragment which contain by TabLayout Viewpager. like this:
Activity -> A Fragment -> B Fragment(TabLayout ViewPager) -> C Fragment(Tab's Fragment) -> D Fragment
I task is switch Fragment C to Fragment D.
Note:- TabLayout ViewPager also contain 3 tab Fragment control by FragmentPagerAdapter.
Tablayout fragment's layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<android.support.design.widget.TabLayout
android:id="#+id/tablayout_postpaid_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabGravity="fill"
app:tabIndicatorColor="#color/white"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/white"
app:tabTextColor="#color/tab_fade_text_color" >
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager_postpaid_service"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- <FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" /> -->
</android.support.v4.view.ViewPager>
Fragment B class:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_select_postpaid_service, container, false);
tablayout = (TabLayout) view.findViewById(R.id.tablayout_postpaid_service);
viewpager = (ViewPager) view.findViewById(R.id.viewpager_postpaid_service);
viewpager.setAdapter(new TabPagerAdapter(getChildFragmentManager(), TabConstants.POSTPAID_SERVICE_TYPE_TABS_FLAG, TabConstants.POSTPAID_SERVICE_TYPE_TABS));
tablayout.post(new Runnable() {
#Override
public void run() {
tablayout.setupWithViewPager(viewpager);
setupTabIcons();
}
});
return view;
}
Fragment C class:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_select_operator, container,
false);
setGridview();
return view;
}
private void setGridview() {
operatorName = new ArrayList<String>();
operatorCode = new ArrayList<String>();
recyclerview = (RecyclerView) view
.findViewById(R.id.select_operator_recycler_view);
recyclerview.setHasFixedSize(true);
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(),
Constants.NO_OF_OPERATOR_GRID);
recyclerview.setLayoutManager(layoutManager);
OperatorGridAdapter adapter = new OperatorGridAdapter(getActivity(),
HomeConstants.OPERATOR_LIST_ICON);
recyclerview.setAdapter(adapter);
recyclerview.addOnItemTouchListener(new RecyclerItemClickListener(
getActivity(),
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
navigateFragment(position);
}
}));
}
private void navigateFragment(int position) {
Fragment fragment = new DFragment();
// FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
//fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(
getResources().getString(R.string.app_name));
Log.d(Constants.ACTIVITY_TAG, "********************");
}
I getting an error
java.lang.IllegalArgumentException: No view found for id 0x7f0a006e (com.recharge:id/container_body) for fragment DFragment{4327cfd0 #2 id=0x7f0a006e}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1259)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1624)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
I've tried many tick and solution but not hit for me .
Please help me short out this problem.
Have you tried?
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new FragmentB()).commit();
and I think the error was quite obvious. The compile says:
not view found for container_body
And in your code:
private void navigateFragment(int position) {
Fragment fragment = new DFragment();
// FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
//fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(
getResources().getString(R.string.app_name));
Log.d(Constants.ACTIVITY_TAG, "********************");
}
I see that you try to use fragmentTransaction.replace(R.id.container_body, fragment); However you just comment the container_body in your layout. That's why the compile told you that it can't find container_body for the fragment to inflate. Maybe that's the problem?
Also it should be helpful if you could post more details about your layout for fragment D.
Let me know if this solve your problem ;)

Categories

Resources