[英]How to save state of toolbar in fragment?
I am new to android.我是 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. Ш在
onCreate(@Nullable Bundle savedInstanceState)
中附加fragment的activity,在创建新事务之前,必须检查activity state是否为null,然后才创建事务并添加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更多细节可以在这里找到: https://developer.android.com/guide/fragments/create#java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.