我的应用程序中有两项活动:
MainActivity(包含3个片段)
AccountEditActivity
在MainActivity中设置片段的代码是:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
// set Home as the default fragment
setFragment(FragmentMainHome.getInstance());
}
private void setFragment(Fragment fragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, fragment);
transaction.commit();
}
FragmentAccount的代码为:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_activity_main_account, container, false);
layout = rootView.findViewById(R.id.layout_fragment_main_account);
etName = (EditText) layout.findViewById(R.id.etNameLabelValue);
etEmail = (EditText) layout.findViewById(R.id.etEmailLabelValue);
etGender = (EditText) layout.findViewById(R.id.etGenderLabelValue);
etPhoneNumber = (EditText) layout.findViewById(R.id.etPhoneNumberLabelValue);
btnEditAccount = (ImageButton) layout.findViewById(R.id.btnEditAccount);
btnManageAddresses = (ImageButton) layout.findViewById(R.id.btnAccountManageAddresses);
btnManageAddresses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
btnEditAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
return rootView;
}
FragmentOrders的代码为:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_activity_main_order_history, container, false);
layout = rootView.findViewById(R.id.layout_fragment_main_order_history);
lvOrders = (ListView) layout.findViewById(R.id.lvOrders);
tvNoOrdersFound = (TextView) layout.findViewById(R.id.tvNoOrdersFound);
final SwipeRefreshLayout pullToRefresh = rootView.findViewById(R.id.swipe_refresh_layout_order_history);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// load orders
pullToRefresh.setRefreshing(false);
}
});
lvOrders.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
return rootView;
}
和类似的代码用于FragmentHome
问题
我可以在片段之间移动,并且视图可以正常工作。 现在从“帐户”片段中,转到“ AccountEditActivity” 我在那里进行了一些更新,然后通过按硬件后退按钮返回到MainActivity
FragmentHome正常显示,但是当我单击FragmentAccount时,屏幕变为空白
现在,如果我单击“主页”片段,然后再次单击“ FragmentAccount”,它将显示正常。
这是怎么了?
答案 0 :(得分:0)
在活动中更好地使用viewpager来显示片段 使用Viewpagers时很容易管理
,您只需将这段代码从onCreate移到onResume
setFragment(FragmentMainHome.getInstance());
为了更好地理解,请查看android中活动的生命周期