I am new to android. I got a toolbar with one button in a fragment, when my emulator changes orientation, another button is added. What do I need to fix it?
I found a solution to the problem. Шn the activity to which the fragment is attached in the onCreate(@Nullable Bundle savedInstanceState)
, before creating a new transaction, you must check the activity state for null, only then create a transaction and add a fragment. Example:
public abstract class SingleFragmentActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_fragment);
if (savedInstanceState == null){
Fragment fragment = createFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fl_single_fragment_container, fragment, fragment.getClass().getSimpleName()).commit();
}
}
abstract Fragment createFragment();
}
more details can be found here: https://developer.android.com/guide/fragments/create#java
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.