Reputation: 17330
in my main activity i have this line to replace fragment with viewgroup
MainActivity:
public class ActivityMain extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.replace(R.id.activity_main_container, new HomeFragment())
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
}
}
activity layout:
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/activity_main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
and my HomeFragment
is:
public class HomeFragment extends Fragment {
public HomeFragment() {
}
@Override
public void onCreate(Bundle saved) {
super.onCreate(saved);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
Log.e("HomeFragment", " onCreateView");
return view;
}
}
now after build application and run that on emulator, my code running duplicate HomeFragment
, how can i prevent this action?
Upvotes: 0
Views: 36
Reputation: 173
Do like this if fragment is already launched don't perform transaction again
private Class mFragmentClass; mFragmentClass = InfoFragment.class;
if (null != mFragmentClass) {
try {
mFragment = (Fragment) mFragmentClass.newInstance();
if(mFragment instanceof (Fragment)mFragmentClass){
FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_navigation_menu, mFragment).commit();
} catch (InstantiationException exception) { exception.printStackTrace();
} catch (IllegalAccessException exception) { exception.printStackTrace(); }
}else {
//do nothing
}
Upvotes: 0
Reputation: 10308
The framework will restore your fragment state when an activity is restored, such as after a configuration change. You should only manipulate fragments the first time an activity is created.
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
// set up your fragments
}
}
Upvotes: 1