问题:当点击viewpager中的一个fragment时,进入另一个不相关的fragment,按返回键返回原来的fragment?
回答:判断初始化动画位置
例子:
传值
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// 获取商品位置
Themes themes = (Themes) parent.getItemAtPosition(position);
// 创建GoodsInfoFragment对象
ThemeFragment fragment = new ThemeFragment();
// 传值
Bundle bundle = new Bundle();
bundle.putString("title", themes.getTitle());
bundle.putString("content", themes.getContent());
bundle.putInt("tag", 1);
fragment.setArguments(bundle);
Fragment yfragment = getParentFragment().getFragmentManager()
.findFragmentByTag("theme");
// 判断是否为null
if (yfragment != null) {
// 移除
getParentFragment().getFragmentManager().beginTransaction()
.remove(yfragment).commit();
}
// 添加
getParentFragment().getFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.add(R.id.main_content, fragment, "theme").commit();
// 显示
MainActivity activity = (MainActivity) getActivity();
activity.replaceMain("theme");
}
接受值
iv_return.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int tag = getArguments().getInt("tag");
// 创建GoodsInfoFragment对象
HomeFragment fragment = new HomeFragment(tag);
Fragment yfragment = getFragmentManager().findFragmentByTag(
"home");
// 判断是否为null
if (yfragment != null) {
// 移除
getFragmentManager().beginTransaction().remove(yfragment)
.commit();
}
// 添加
getFragmentManager()
.beginTransaction()
.setTransition(
FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.add(R.id.main_content, fragment, "home").commit();
// 显示
mainActivity.replaceMain("home");
}
});
重写方法
private int id;
public HomeFragment() {
}
public HomeFragment(int id) {
this.id = id;
}
判断初始化
//判断 初始化动画位置
if (this.id == 1) {
animation = new TranslateAnimation(offset, position_one, 0, 0);
} else {
animation = new TranslateAnimation(position_one, offset, 0, 0);
}
currIndex = this.id;
mPager.setCurrentItem(currIndex);