我有两个活动,每个活动都有一个片段加载。在第一个活动中,我有一个片段,它有一个列表视图,当我点击列表视图项目时,它使用意图将我带到另一个活动。片段在第二个活动中加载,直到这里它工作正常。
现在当我点击设备的后退按钮,再次回到列表视图时,我必须点击2到3次才能回到之前的列表视图活动,在我回到第一个活动之前,第二个活动或片段重新加载了好几次。
无法理解这个问题。
先谢谢了!!!。
在第一个活动中,我是这样加载碎片的
fragment = new GrowSapceTutorialFragment();
fragmentManager = getSupportFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container_grow_tutorial, fragment);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
对于第1个活动中的后退按钮,在growspaceTutorialfragment中的oncreate viewenter代码为:。
@Override
public void onBackPressed() {
super.onBackPressed();
在growspaceTutorialfragment的oncreate viewenter代码这里。
listViewTip.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for(int i=0; i<=position;i++){
name = dataModelArrayList.get(position).getTitle().toString();
description = dataModelArrayList.get(position).getDescription().toString();
image = dataModelArrayList.get(position).getImageUrl().toString();
tipIntent = new Intent(getActivity(), TipDetailsActivity.class);
tipIntent.putExtra("Title",name);
tipIntent.putExtra("Des", description);
tipIntent.putExtra("Image", image);
startActivity(tipIntent);
在我的Tip details Activity(第2个活动)中。
tipImage = findViewById(R.id.tipImageView);
title = getIntent().getStringExtra("Title");
description = getIntent().getStringExtra("Des");
image = getIntent().getStringExtra("Image");
Picasso.get().load(image).into(tipImage);
bundle = new Bundle();
bundle.putString("Title",title);
bundle.putString("Des", description);
fragment = new TipDetailsFragment();
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragment.setArguments(bundle);
fragmentTransaction.detach(fragment);
fragmentTransaction.attach(fragment);
fragmentTransaction.replace(R.id.frame_container, fragment);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
Tip Details Activity中的后退按钮是由以下方式处理的。
@Override
public void onBackPressed() {
super.onBackPressed();
}
Tip Details Fragment。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tip_details, container, false);
title = view.findViewById(R.id.textViewTipTitle);
description = view.findViewById(R.id.textViewDescription);
bundle = getArguments();
tipTitle = bundle.getString("Title");
tipDes = bundle.getString("Des");
title.setText(tipTitle);
description.setText(tipDes);
return view;
}
活动和片段都有自己的生命周期。当你加载第二个活动时。当你按下后退键时,第二个活动被杀死,第一个活动被放大到视图中。你需要回到你的代码中,简化你的导航结构,或者发布你的导航代码,以获得进一步的帮助。干杯。